zhipeng93 commented on code in PR #196: URL: https://github.com/apache/flink-ml/pull/196#discussion_r1066574806
########## flink-ml-lib/src/main/java/org/apache/flink/ml/feature/standardscaler/OnlineStandardScaler.java: ########## @@ -0,0 +1,215 @@ +/* + * 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.feature.standardscaler; + +import org.apache.flink.api.common.state.ListState; +import org.apache.flink.api.common.state.ListStateDescriptor; +import org.apache.flink.api.common.typeinfo.Types; +import org.apache.flink.iteration.operator.OperatorStateUtils; +import org.apache.flink.ml.api.Estimator; +import org.apache.flink.ml.common.datastream.DataStreamUtils; +import org.apache.flink.ml.linalg.BLAS; +import org.apache.flink.ml.linalg.DenseVector; +import org.apache.flink.ml.linalg.Vector; +import org.apache.flink.ml.linalg.Vectors; +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.streaming.api.datastream.DataStream; +import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction; +import org.apache.flink.streaming.api.windowing.windows.Window; +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 java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * An Estimator which implements the online standard scaling algorithm, which is the online version + * of {@link StandardScaler}. + * + * <p>OnlineStandardScaler splits the input data by the user-specified window strategy (i.e., {@link + * org.apache.flink.ml.common.param.HasWindows}). For each window, it computes the mean and standard + * deviation using the data seen so far (i.e., not only the data in the current window, but also the + * history data). The model data generated by OnlineStandardScaler is a model stream. There is one + * model data for each window. + * + * <p>During the inference phase (i.e., using {@link OnlineStandardScalerModel} for prediction), + * users could output the model version that is used for predicting each data point. Moreover, + * + * <ul> + * <li>When the train data and test data both contains event time, users could specify the maximum + * difference between timestamp of the input and model data ({@link + * org.apache.flink.ml.common.param.HasMaxAllowedModelDelayMs}), which enforces to use a + * relatively fresh model for prediction. + * <li>Otherwise, the prediction process always use the current model data for prediction. + * </ul> + */ +public class OnlineStandardScaler + implements Estimator<OnlineStandardScaler, OnlineStandardScalerModel>, + OnlineStandardScalerParams<OnlineStandardScaler> { + + private final Map<Param<?>, Object> paramMap = new HashMap<>(); + + public OnlineStandardScaler() { + ParamUtils.initializeMapWithDefaultValues(paramMap, this); + } + + @Override + public OnlineStandardScalerModel fit(Table... inputs) { + Preconditions.checkArgument(inputs.length == 1); + StreamTableEnvironment tEnv = + (StreamTableEnvironment) ((TableImpl) inputs[0]).getTableEnvironment(); + DataStream<StandardScalerModelData> modelData = + DataStreamUtils.windowAllAndProcess( + tEnv.toDataStream(inputs[0]), + getWindows(), + new ComputeModelDataFunction<>(getInputCol())); + + OnlineStandardScalerModel model = + new OnlineStandardScalerModel().setModelData(tEnv.fromDataStream(modelData)); + ReadWriteUtils.updateExistingParams(model, paramMap); + return model; + } + + private static class ComputeModelDataFunction<W extends Window> + extends ProcessAllWindowFunction<Row, StandardScalerModelData, W> { + + private final String inputCol; + + public ComputeModelDataFunction(String inputCol) { + this.inputCol = inputCol; + } + + @Override + public void process( + ProcessAllWindowFunction<Row, StandardScalerModelData, W>.Context context, + Iterable<Row> iterable, + Collector<StandardScalerModelData> collector) + throws Exception { + ListState<DenseVector> sumState = + context.globalState() + .getListState( + new ListStateDescriptor<>( + "sumState", DenseVectorTypeInfo.INSTANCE)); + ListState<DenseVector> squaredSumState = + context.globalState() + .getListState( + new ListStateDescriptor<>( + "squaredSumState", DenseVectorTypeInfo.INSTANCE)); + ListState<Long> numElementsState = + context.globalState() + .getListState( + new ListStateDescriptor<>("numElementsState", Types.LONG)); + ListState<Long> modelVersionState = + context.globalState() + .getListState( + new ListStateDescriptor<>("modelVersionState", Types.LONG)); + DenseVector sum = + OperatorStateUtils.getUniqueElement(sumState, "sumState").orElse(null); + DenseVector squaredSum = + OperatorStateUtils.getUniqueElement(squaredSumState, "squaredSumState") + .orElse(null); + long numElements = + OperatorStateUtils.getUniqueElement(numElementsState, "numElementsState") + .orElse(0L); + long modelVersion = + OperatorStateUtils.getUniqueElement(modelVersionState, "modelVersionState") + .orElse(0L); + + long numElementsBefore = numElements; + for (Row element : iterable) { + Vector inputVec = + ((Vector) Objects.requireNonNull(element.getField(inputCol))).clone(); + if (numElements == 0) { Review Comment: Puting it inside the loop is to get the size of the vector for initializing `sum` and `squareSum`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
