Search in sources :

Example 61 with SparseVector

use of com.alibaba.alink.common.linalg.SparseVector in project Alink by alibaba.

the class QuantileDiscretizerModelMapperTest method testDropLast.

@Test
public void testDropLast() throws Exception {
    Params params = new Params().set(QuantileDiscretizerPredictParams.ENCODE, HasEncodeWithoutWoe.Encode.VECTOR).set(QuantileDiscretizerPredictParams.SELECTED_COLS, new String[] { "col2", "col3" }).set(QuantileDiscretizerPredictParams.DROP_LAST, true);
    QuantileDiscretizerModelMapper mapper = new QuantileDiscretizerModelMapper(modelSchema, dataSchema, params);
    mapper.loadModel(model);
    assertEquals(mapper.map(defaultRow), Row.of("a", new SparseVector(3, new int[] { 0 }, new double[] { 1.0 }), new SparseVector(3)));
    assertEquals(mapper.map(nullElseRow), Row.of("b", new SparseVector(3, new int[] { 2 }, new double[] { 1.0 }), new SparseVector(3, new int[] { 1 }, new double[] { 1.0 })));
}
Also used : QuantileDiscretizerPredictParams(com.alibaba.alink.params.feature.QuantileDiscretizerPredictParams) Params(org.apache.flink.ml.api.misc.param.Params) SparseVector(com.alibaba.alink.common.linalg.SparseVector) Test(org.junit.Test)

Example 62 with SparseVector

use of com.alibaba.alink.common.linalg.SparseVector in project Alink by alibaba.

the class EvaluationUtilTest method assertBinaryMetrics.

private void assertBinaryMetrics(BaseMetricsSummary baseMetric) {
    Assert.assertTrue(baseMetric instanceof BinaryMetricsSummary);
    BinaryMetricsSummary metrics = (BinaryMetricsSummary) baseMetric;
    Assert.assertEquals(5, metrics.total);
    Assert.assertEquals(2.987, metrics.logLoss, 0.01);
    Assert.assertEquals(metrics.positiveBin.length, 100000);
    SparseVector vec = new SparseVector(100000, new int[] { 70000, 80000, 90000 }, new double[] { 1, 1, 1 });
    for (int i = 0; i < metrics.positiveBin.length; i++) {
        Assert.assertEquals((int) vec.get(i), metrics.positiveBin[i]);
    }
    Assert.assertEquals(metrics.negativeBin.length, 100000);
    vec = new SparseVector(100000, new int[] { 60000, 75000 }, new double[] { 1, 1 });
    for (int i = 0; i < metrics.negativeBin.length; i++) {
        Assert.assertEquals((int) vec.get(i), metrics.negativeBin[i]);
    }
}
Also used : SparseVector(com.alibaba.alink.common.linalg.SparseVector)

Example 63 with SparseVector

use of com.alibaba.alink.common.linalg.SparseVector in project Alink by alibaba.

the class SparseVectorSummaryTest method summarizer.

private SparseVectorSummary summarizer() {
    SparseVector[] data = new SparseVector[] { new SparseVector(5, new int[] { 0, 1, 2 }, new double[] { 1.0, -1.0, 3.0 }), new SparseVector(5, new int[] { 1, 2, 3 }, new double[] { 2.0, -2.0, 3.0 }), new SparseVector(5, new int[] { 2, 3, 4 }, new double[] { 3.0, -3.0, 3.0 }), new SparseVector(5, new int[] { 0, 2, 3 }, new double[] { 4.0, -4.0, 3.0 }), new SparseVector(5, new int[] { 0, 1, 4 }, new double[] { 5.0, -5.0, 3.0 }) };
    SparseVectorSummarizer summarizer = new SparseVectorSummarizer();
    for (SparseVector aData : data) {
        summarizer.visit(aData);
    }
    return (SparseVectorSummary) summarizer.toSummary();
}
Also used : SparseVector(com.alibaba.alink.common.linalg.SparseVector)

Example 64 with SparseVector

use of com.alibaba.alink.common.linalg.SparseVector in project Alink by alibaba.

the class KMeansTrainBatchOp method linkFrom.

@Override
public KMeansTrainBatchOp linkFrom(BatchOperator<?>... inputs) {
    BatchOperator<?> in = checkAndGetFirst(inputs);
    final int maxIter = this.getMaxIter();
    final double tol = this.getEpsilon();
    final String vectorColName = this.getVectorCol();
    final DistanceType distanceType = getDistanceType();
    FastDistance distance = distanceType.getFastDistance();
    Tuple2<DataSet<Vector>, DataSet<BaseVectorSummary>> statistics = StatisticsHelper.summaryHelper(in, null, vectorColName);
    DataSet<Integer> vectorSize = statistics.f1.map(new MapFunction<BaseVectorSummary, Integer>() {

        private static final long serialVersionUID = 4184586558834055401L;

        @Override
        public Integer map(BaseVectorSummary value) {
            Preconditions.checkArgument(value.count() > 0, "The train dataset is empty!");
            return value.vectorSize();
        }
    });
    DataSet<FastDistanceVectorData> data = statistics.f0.rebalance().map(new RichMapFunction<Vector, FastDistanceVectorData>() {

        private static final long serialVersionUID = -7443226889326704768L;

        private int vectorSize;

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

        @Override
        public FastDistanceVectorData map(Vector value) {
            if (value instanceof SparseVector) {
                ((SparseVector) value).setSize(vectorSize);
            }
            return distance.prepareVectorData(Row.of(value), 0);
        }
    }).withBroadcastSet(vectorSize, VECTOR_SIZE);
    DataSet<FastDistanceMatrixData> initCentroid = KMeansInitCentroids.initKmeansCentroids(data, distance, this.getParams(), vectorSize, getRandomSeed());
    DataSet<Row> finalCentroid = iterateICQ(initCentroid, data, vectorSize, maxIter, tol, distance, HasKMeansWithHaversineDistanceType.DistanceType.valueOf(distanceType.name()), vectorColName, null, null);
    this.setOutput(finalCentroid, new KMeansModelDataConverter().getModelSchema());
    return this;
}
Also used : Configuration(org.apache.flink.configuration.Configuration) DataSet(org.apache.flink.api.java.DataSet) FastDistanceVectorData(com.alibaba.alink.operator.common.distance.FastDistanceVectorData) HasKMeansWithHaversineDistanceType(com.alibaba.alink.params.shared.clustering.HasKMeansWithHaversineDistanceType) SparseVector(com.alibaba.alink.common.linalg.SparseVector) FastDistance(com.alibaba.alink.operator.common.distance.FastDistance) BaseVectorSummary(com.alibaba.alink.operator.common.statistics.basicstatistic.BaseVectorSummary) Vector(com.alibaba.alink.common.linalg.Vector) SparseVector(com.alibaba.alink.common.linalg.SparseVector) KMeansModelDataConverter(com.alibaba.alink.operator.common.clustering.kmeans.KMeansModelDataConverter) FastDistanceMatrixData(com.alibaba.alink.operator.common.distance.FastDistanceMatrixData) RichMapFunction(org.apache.flink.api.common.functions.RichMapFunction) Row(org.apache.flink.types.Row)

Example 65 with SparseVector

use of com.alibaba.alink.common.linalg.SparseVector 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

SparseVector (com.alibaba.alink.common.linalg.SparseVector)125 Test (org.junit.Test)63 DenseVector (com.alibaba.alink.common.linalg.DenseVector)60 Params (org.apache.flink.ml.api.misc.param.Params)45 Row (org.apache.flink.types.Row)45 Vector (com.alibaba.alink.common.linalg.Vector)40 TableSchema (org.apache.flink.table.api.TableSchema)27 ArrayList (java.util.ArrayList)21 TypeInformation (org.apache.flink.api.common.typeinfo.TypeInformation)15 HashMap (java.util.HashMap)12 Tuple2 (org.apache.flink.api.java.tuple.Tuple2)12 List (java.util.List)11 DenseMatrix (com.alibaba.alink.common.linalg.DenseMatrix)10 MTable (com.alibaba.alink.common.MTable)7 BaseVectorSummary (com.alibaba.alink.operator.common.statistics.basicstatistic.BaseVectorSummary)6 CollectSinkStreamOp (com.alibaba.alink.operator.stream.sink.CollectSinkStreamOp)6 Map (java.util.Map)6 MemSourceBatchOp (com.alibaba.alink.operator.batch.source.MemSourceBatchOp)5 VectorAssemblerParams (com.alibaba.alink.params.dataproc.vector.VectorAssemblerParams)5 OneHotPredictParams (com.alibaba.alink.params.feature.OneHotPredictParams)5