Search in sources :

Example 1 with BisectingKMeansModelDataConverter

use of com.alibaba.alink.operator.common.clustering.BisectingKMeansModelDataConverter 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)

Aggregations

DenseVector (com.alibaba.alink.common.linalg.DenseVector)1 SparseVector (com.alibaba.alink.common.linalg.SparseVector)1 Vector (com.alibaba.alink.common.linalg.Vector)1 ClusterSummary (com.alibaba.alink.operator.common.clustering.BisectingKMeansModelData.ClusterSummary)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 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 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 Tuple3 (org.apache.flink.api.java.tuple.Tuple3)1 Configuration (org.apache.flink.configuration.Configuration)1 Row (org.apache.flink.types.Row)1