
org.apache.flink.ml.stats.chisqtest.ChiSqTest Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.ml.stats.chisqtest;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.iteration.operator.OperatorStateUtils;
import org.apache.flink.ml.api.AlgoOperator;
import org.apache.flink.ml.common.broadcast.BroadcastUtils;
import org.apache.flink.ml.common.param.HasFlatten;
import org.apache.flink.ml.linalg.DenseVector;
import org.apache.flink.ml.linalg.Vector;
import org.apache.flink.ml.linalg.typeinfo.DenseVectorTypeInfo;
import org.apache.flink.ml.param.Param;
import org.apache.flink.ml.util.ParamUtils;
import org.apache.flink.ml.util.ReadWriteUtils;
import org.apache.flink.runtime.state.StateInitializationContext;
import org.apache.flink.runtime.state.StateSnapshotContext;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.BoundedOneInput;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.internal.TableImpl;
import org.apache.flink.types.Row;
import org.apache.flink.util.Collector;
import org.apache.flink.util.Preconditions;
import org.apache.commons.math3.distribution.ChiSquaredDistribution;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* An AlgoOperator which implements the Chi-square test algorithm.
*
* Chi-square Test computes the statistics of independence of variables in a contingency table,
* e.g., p-value, and DOF(degree of freedom) for each input feature. The contingency table is
* constructed from the observed categorical values.
*
*
The input of this algorithm is a table containing a labelColumn of numerical type and a
* featuresColumn of vector type. Each index in the input vector represents a feature to be tested.
* By default, the output of this algorithm is a table containing a single row with the following
* columns, each of which has one value per feature.
*
*
* - "pValues": vector
*
- "degreesOfFreedom": int array
*
- "statistics": vector
*
*
* The output of this algorithm can be flattened to multiple rows by setting {@link
* HasFlatten#FLATTEN} to true, which would contain the following columns:
*
*
* - "featureIndex": int
*
- "pValue": double
*
- "degreeOfFreedom": int
*
- "statistic": double
*
*
* See: http://en.wikipedia.org/wiki/Chi-squared_test.
*/
public class ChiSqTest implements AlgoOperator, ChiSqTestParams {
private final Map, Object> paramMap = new HashMap<>();
public ChiSqTest() {
ParamUtils.initializeMapWithDefaultValues(paramMap, this);
}
@Override
public Table[] transform(Table... inputs) {
Preconditions.checkArgument(inputs.length == 1);
final String bcCategoricalMarginsKey = "bcCategoricalMarginsKey";
final String bcLabelMarginsKey = "bcLabelMarginsKey";
final String featuresCol = getFeaturesCol();
final String labelCol = getLabelCol();
StreamTableEnvironment tEnv =
(StreamTableEnvironment) ((TableImpl) inputs[0]).getTableEnvironment();
SingleOutputStreamOperator> indexAndFeatureAndLabel =
tEnv.toDataStream(inputs[0])
.flatMap(new ExtractIndexAndFeatureAndLabel(featuresCol, labelCol));
DataStream> observedFreq =
indexAndFeatureAndLabel
.keyBy(Tuple3::hashCode)
.transform(
"GenerateObservedFrequencies",
Types.TUPLE(Types.INT, Types.DOUBLE, Types.DOUBLE, Types.LONG),
new GenerateObservedFrequencies());
SingleOutputStreamOperator> filledObservedFreq =
observedFreq
.transform(
"filledObservedFreq",
Types.TUPLE(Types.INT, Types.DOUBLE, Types.DOUBLE, Types.LONG),
new FillFrequencyTable())
.setParallelism(1);
DataStream> categoricalMargins =
observedFreq
.keyBy(tuple -> new Tuple2<>(tuple.f0, tuple.f1).hashCode())
.transform(
"AggregateCategoricalMargins",
Types.TUPLE(Types.INT, Types.DOUBLE, Types.LONG),
new AggregateCategoricalMargins());
DataStream> labelMargins =
observedFreq
.keyBy(tuple -> new Tuple2<>(tuple.f0, tuple.f2).hashCode())
.transform(
"AggregateLabelMargins",
Types.TUPLE(Types.INT, Types.DOUBLE, Types.LONG),
new AggregateLabelMargins());
Function>, DataStream>> function =
dataStreams -> {
DataStream stream = dataStreams.get(0);
return stream.map(
new ChiSqFunc(bcCategoricalMarginsKey, bcLabelMarginsKey),
Types.TUPLE(Types.INT, Types.DOUBLE, Types.INT));
};
HashMap> bcMap =
new HashMap>() {
{
put(bcCategoricalMarginsKey, categoricalMargins);
put(bcLabelMarginsKey, labelMargins);
}
};
DataStream> categoricalStatistics =
BroadcastUtils.withBroadcastStream(
Collections.singletonList(filledObservedFreq), bcMap, function);
boolean flatten = getFlatten();
RowTypeInfo outputTypeInfo;
if (flatten) {
outputTypeInfo =
new RowTypeInfo(
new TypeInformation[] {
Types.INT, Types.DOUBLE, Types.INT, Types.DOUBLE
},
new String[] {
"featureIndex", "pValue", "degreeOfFreedom", "statistic"
});
} else {
outputTypeInfo =
new RowTypeInfo(
new TypeInformation[] {
DenseVectorTypeInfo.INSTANCE,
Types.PRIMITIVE_ARRAY(Types.INT),
DenseVectorTypeInfo.INSTANCE
},
new String[] {"pValues", "degreesOfFreedom", "statistics"});
}
SingleOutputStreamOperator chiSqTestResult =
categoricalStatistics
.transform(
"chiSqTestResult", outputTypeInfo, new AggregateChiSqFunc(flatten))
.setParallelism(1);
return new Table[] {tEnv.fromDataStream(chiSqTestResult)};
}
@Override
public void save(String path) throws IOException {
ReadWriteUtils.saveMetadata(this, path);
}
public static ChiSqTest load(StreamTableEnvironment tEnv, String path) throws IOException {
return ReadWriteUtils.loadStageParam(path);
}
@Override
public Map, Object> getParamMap() {
return paramMap;
}
private static class ExtractIndexAndFeatureAndLabel
extends RichFlatMapFunction> {
private final String featuresCol;
private final String labelCol;
public ExtractIndexAndFeatureAndLabel(String featuresCol, String labelCol) {
this.featuresCol = featuresCol;
this.labelCol = labelCol;
}
@Override
public void flatMap(Row row, Collector> collector) {
Double label = ((Number) row.getFieldAs(labelCol)).doubleValue();
Vector features = row.getFieldAs(featuresCol);
for (int i = 0; i < features.size(); i++) {
collector.collect(Tuple3.of(i, features.get(i), label));
}
}
}
/**
* Computes the frequency of each feature value at different indices by labels. An output record
* (indexA, featureValueB, labelC, countD) represents that A feature value {featureValueB} with
* label {labelC} at index {indexA} has appeared {countD} times in the input table.
*/
private static class GenerateObservedFrequencies
extends AbstractStreamOperator>
implements OneInputStreamOperator<
Tuple3, Tuple4>,
BoundedOneInput {
private Map, Long> cntMap = new HashMap<>();
private ListState