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");
}
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;
}
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;
}
Aggregations