Search in sources :

Example 1 with ClusterSummary

use of com.alibaba.alink.operator.common.clustering.BisectingKMeansModelData.ClusterSummary in project Alink by alibaba.

the class BisectingKMeansTrainBatchOp method getOrSplitClusters.

/**
 * If at the cluster dividing step, divide current active clusters; Otherwise, just copy existing clusters.
 *
 * @param clustersSummariesAndIterInfo clusterId, clusterSummary, IterInfo
 * @param k                            cluster number
 * @return original clusters and new clusters.
 */
private static DataSet<Tuple3<Long, ClusterSummary, IterInfo>> getOrSplitClusters(DataSet<Tuple3<Long, ClusterSummary, IterInfo>> clustersSummariesAndIterInfo, final int k, final int minDivisibleClusterSize, final int seed) {
    return clustersSummariesAndIterInfo.partitionCustom(new Partitioner<Integer>() {

        private static final long serialVersionUID = -9210153686004045278L;

        @Override
        public int partition(Integer key, int numPartitions) {
            return 0;
        }
    }, new KeySelector<Tuple3<Long, ClusterSummary, IterInfo>, Integer>() {

        private static final long serialVersionUID = 1038545655756366007L;

        @Override
        public Integer getKey(Tuple3<Long, ClusterSummary, IterInfo> value) {
            return 0;
        }
    }).mapPartition(new RichMapPartitionFunction<Tuple3<Long, ClusterSummary, IterInfo>, Tuple3<Long, ClusterSummary, IterInfo>>() {

        private static final long serialVersionUID = 673707294676457023L;

        private transient Random random;

        @Override
        public void open(Configuration parameters) {
            if (random == null && getRuntimeContext().getIndexOfThisSubtask() == 0) {
                random = new Random(seed);
            }
        }

        @Override
        public void mapPartition(Iterable<Tuple3<Long, ClusterSummary, IterInfo>> summaries, Collector<Tuple3<Long, ClusterSummary, IterInfo>> out) {
            if (getRuntimeContext().getIndexOfThisSubtask() > 0) {
                return;
            }
            List<Tuple3<Long, ClusterSummary, IterInfo>> clustersAndIterInfo = new ArrayList<>();
            summaries.forEach(clustersAndIterInfo::add);
            // At the first step of bisecting
            if (clustersAndIterInfo.get(0).f2.doBisectionInStep()) {
                // find all splitable clusters
                Set<Long> splitableClusters = findSplitableClusters(clustersAndIterInfo, k, minDivisibleClusterSize);
                boolean shouldStopSplit = (splitableClusters.size() + getNumLeaf(clustersAndIterInfo)) >= k;
                // split clusters
                clustersAndIterInfo.forEach(t -> {
                    assert (!t.f2.isDividing);
                    assert (!t.f2.isNew);
                    t.f2.shouldStopSplit = shouldStopSplit;
                    if (splitableClusters.contains(t.f0)) {
                        ClusterSummary summary = t.f1;
                        IterInfo newCenterIterInfo = new IterInfo(t.f2.maxIter, t.f2.bisectingStepNo, t.f2.innerIterStepNo, false, true, shouldStopSplit);
                        Tuple2<DenseVector, DenseVector> newCenters = initialSplitCenter(summary.center, random);
                        ClusterSummary leftChildSummary = new ClusterSummary();
                        leftChildSummary.center = newCenters.f0;
                        ClusterSummary rightChildSummary = new ClusterSummary();
                        rightChildSummary.center = newCenters.f1;
                        t.f2.isDividing = true;
                        out.collect(t);
                        out.collect(Tuple3.of(leftChildIndex(t.f0), leftChildSummary, newCenterIterInfo));
                        out.collect(Tuple3.of(rightChildIndex(t.f0), rightChildSummary, newCenterIterInfo));
                    } else {
                        out.collect(t);
                    }
                });
            } else {
                // copy existing clusters
                clustersAndIterInfo.forEach(out::collect);
            }
        }
    }).name("get_or_split_clusters");
}
Also used : Configuration(org.apache.flink.configuration.Configuration) RichMapPartitionFunction(org.apache.flink.api.common.functions.RichMapPartitionFunction) ClusterSummary(com.alibaba.alink.operator.common.clustering.BisectingKMeansModelData.ClusterSummary) ArrayList(java.util.ArrayList) Random(java.util.Random) Tuple3(org.apache.flink.api.java.tuple.Tuple3) Collector(org.apache.flink.util.Collector) DenseVector(com.alibaba.alink.common.linalg.DenseVector)

Example 2 with ClusterSummary

use of com.alibaba.alink.operator.common.clustering.BisectingKMeansModelData.ClusterSummary in project Alink by alibaba.

the class BisectingKMeansTrainBatchOp method linkFrom.

/**
 * The bisecting kmeans algorithm has nested loops. In the outer loop, cluster centers
 * are splited. In the inner loop, the splited centers are iteratively refined.
 * However, there lacks nested loop semantic in Flink, so we have to flatten the nested loop
 * in our implementation.
 */
@Override
public BisectingKMeansTrainBatchOp linkFrom(BatchOperator<?>... inputs) {
    BatchOperator<?> in = checkAndGetFirst(inputs);
    // get the input parameter's value
    final DistanceType distanceType = getDistanceType();
    final int k = this.getK();
    final int maxIter = this.getMaxIter();
    final String vectorColName = this.getVectorCol();
    final int minDivisibleClusterSize = this.getMinDivisibleClusterSize();
    ContinuousDistance distance = distanceType.getFastDistance();
    Tuple2<DataSet<Vector>, DataSet<BaseVectorSummary>> vectorsAndStat = StatisticsHelper.summaryHelper(in, null, vectorColName);
    DataSet<Integer> dim = vectorsAndStat.f1.map(new MapFunction<BaseVectorSummary, Integer>() {

        private static final long serialVersionUID = 5358843841535961680L;

        @Override
        public Integer map(BaseVectorSummary value) {
            Preconditions.checkArgument(value.count() > 0, "The train dataset is empty!");
            return value.vectorSize();
        }
    });
    // tuple: sampleId, features, assignment
    DataSet<Tuple3<Long, Vector, Long>> initialAssignment = DataSetUtils.zipWithUniqueId(vectorsAndStat.f0).map(new RichMapFunction<Tuple2<Long, Vector>, Tuple3<Long, Vector, Long>>() {

        private static final long serialVersionUID = -6036596630416015773L;

        private int vectorSize;

        @Override
        public void open(Configuration params) {
            vectorSize = (int) this.getRuntimeContext().getBroadcastVariable(VECTOR_SIZE).get(0);
        }

        @Override
        public Tuple3<Long, Vector, Long> map(Tuple2<Long, Vector> value) {
            if (value.f1 instanceof SparseVector) {
                ((SparseVector) value.f1).setSize(vectorSize);
            }
            return Tuple3.of(value.f0, value.f1, ROOT_INDEX);
        }
    }).withBroadcastSet(dim, VECTOR_SIZE);
    DataSet<Tuple2<Long, ClusterSummary>> clustersSummaries = summary(initialAssignment.project(2, 1), dim, distanceType);
    DataSet<Tuple3<Long, ClusterSummary, IterInfo>> clustersSummariesAndIterInfo = clustersSummaries.map(new MapFunction<Tuple2<Long, ClusterSummary>, Tuple3<Long, ClusterSummary, IterInfo>>() {

        private static final long serialVersionUID = -3883958936263294331L;

        @Override
        public Tuple3<Long, ClusterSummary, IterInfo> map(Tuple2<Long, ClusterSummary> value) {
            return Tuple3.of(value.f0, value.f1, new IterInfo(maxIter));
        }
    }).withForwardedFields("f0;f1");
    IterativeDataSet<Tuple3<Long, ClusterSummary, IterInfo>> loop = clustersSummariesAndIterInfo.iterate(Integer.MAX_VALUE);
    DataSet<Tuple1<IterInfo>> iterInfo = loop.<Tuple1<IterInfo>>project(2).first(1);
    // Get all cluster summaries. Split clusters if at the first step of inner iterations.
    DataSet<Tuple3<Long, ClusterSummary, IterInfo>> allClusters = getOrSplitClusters(loop, k, minDivisibleClusterSize, getRandomSeed());
    DataSet<Long> divisibleClusterIndices = getDivisibleClusterIndices(allClusters);
    DataSet<Tuple2<Long, DenseVector>> newClusterCenters = getNewClusterCenters(allClusters);
    DataSet<Tuple3<Long, Vector, Long>> newAssignment = updateAssignment(initialAssignment, divisibleClusterIndices, newClusterCenters, distance, iterInfo);
    DataSet<Tuple2<Long, ClusterSummary>> newClusterSummaries = summary(newAssignment.project(2, 1), dim, distanceType);
    DataSet<Tuple3<Long, ClusterSummary, IterInfo>> updatedClusterSummariesWithIterInfo = updateClusterSummariesAndIterInfo(allClusters, newClusterSummaries);
    DataSet<Integer> stopCriterion = iterInfo.flatMap(new FlatMapFunction<Tuple1<IterInfo>, Integer>() {

        private static final long serialVersionUID = -4258243788034193744L;

        @Override
        public void flatMap(Tuple1<IterInfo> value, Collector<Integer> out) {
            if (!(value.f0.atLastInnerIterStep() && value.f0.atLastBisectionStep())) {
                out.collect(0);
            }
        }
    });
    DataSet<Tuple2<Long, ClusterSummary>> finalClusterSummaries = loop.closeWith(updatedClusterSummariesWithIterInfo, stopCriterion).project(0, 1);
    DataSet<Row> modelRows = finalClusterSummaries.mapPartition(new SaveModel(distanceType, vectorColName, k)).withBroadcastSet(dim, VECTOR_SIZE).setParallelism(1);
    this.setOutput(modelRows, new BisectingKMeansModelDataConverter().getModelSchema());
    return this;
}
Also used : Configuration(org.apache.flink.configuration.Configuration) DataSet(org.apache.flink.api.java.DataSet) IterativeDataSet(org.apache.flink.api.java.operators.IterativeDataSet) SparseVector(com.alibaba.alink.common.linalg.SparseVector) MapFunction(org.apache.flink.api.common.functions.MapFunction) FlatMapFunction(org.apache.flink.api.common.functions.FlatMapFunction) RichMapFunction(org.apache.flink.api.common.functions.RichMapFunction) BisectingKMeansModelDataConverter(com.alibaba.alink.operator.common.clustering.BisectingKMeansModelDataConverter) BaseVectorSummary(com.alibaba.alink.operator.common.statistics.basicstatistic.BaseVectorSummary) Vector(com.alibaba.alink.common.linalg.Vector) DenseVector(com.alibaba.alink.common.linalg.DenseVector) SparseVector(com.alibaba.alink.common.linalg.SparseVector) ClusterSummary(com.alibaba.alink.operator.common.clustering.BisectingKMeansModelData.ClusterSummary) ContinuousDistance(com.alibaba.alink.operator.common.distance.ContinuousDistance) Tuple1(org.apache.flink.api.java.tuple.Tuple1) RichMapFunction(org.apache.flink.api.common.functions.RichMapFunction) Tuple2(org.apache.flink.api.java.tuple.Tuple2) Tuple3(org.apache.flink.api.java.tuple.Tuple3) Row(org.apache.flink.types.Row)

Example 3 with ClusterSummary

use of com.alibaba.alink.operator.common.clustering.BisectingKMeansModelData.ClusterSummary in project Alink by alibaba.

the class BisectingKMeansModelDataConverter method deserializeModel.

@Override
public BisectingKMeansModelData deserializeModel(Params meta, Iterable<String> data) {
    BisectingKMeansModelData modelData = new BisectingKMeansModelData();
    modelData.k = meta.get(BisectingKMeansTrainParams.K);
    modelData.vectorSize = meta.get(HasVectorSizeDv100.VECTOR_SIZE);
    modelData.distanceType = meta.get(BisectingKMeansTrainParams.DISTANCE_TYPE);
    modelData.vectorColName = meta.get(BisectingKMeansTrainParams.VECTOR_COL);
    modelData.summaries = new HashMap<>();
    for (String c : data) {
        ClusterSummary summary = gson.fromJson(c, ClusterSummary.class);
        long clusterId = summary.clusterId;
        modelData.summaries.put(clusterId, summary);
    }
    return modelData;
}
Also used : ClusterSummary(com.alibaba.alink.operator.common.clustering.BisectingKMeansModelData.ClusterSummary)

Aggregations

ClusterSummary (com.alibaba.alink.operator.common.clustering.BisectingKMeansModelData.ClusterSummary)3 DenseVector (com.alibaba.alink.common.linalg.DenseVector)2 Tuple3 (org.apache.flink.api.java.tuple.Tuple3)2 Configuration (org.apache.flink.configuration.Configuration)2 SparseVector (com.alibaba.alink.common.linalg.SparseVector)1 Vector (com.alibaba.alink.common.linalg.Vector)1 BisectingKMeansModelDataConverter (com.alibaba.alink.operator.common.clustering.BisectingKMeansModelDataConverter)1 ContinuousDistance (com.alibaba.alink.operator.common.distance.ContinuousDistance)1 BaseVectorSummary (com.alibaba.alink.operator.common.statistics.basicstatistic.BaseVectorSummary)1 ArrayList (java.util.ArrayList)1 Random (java.util.Random)1 FlatMapFunction (org.apache.flink.api.common.functions.FlatMapFunction)1 MapFunction (org.apache.flink.api.common.functions.MapFunction)1 RichMapFunction (org.apache.flink.api.common.functions.RichMapFunction)1 RichMapPartitionFunction (org.apache.flink.api.common.functions.RichMapPartitionFunction)1 DataSet (org.apache.flink.api.java.DataSet)1 IterativeDataSet (org.apache.flink.api.java.operators.IterativeDataSet)1 Tuple1 (org.apache.flink.api.java.tuple.Tuple1)1 Tuple2 (org.apache.flink.api.java.tuple.Tuple2)1 Row (org.apache.flink.types.Row)1