lindong28 commented on code in PR #97:
URL: https://github.com/apache/flink-ml/pull/97#discussion_r891853412
##########
flink-ml-core/src/main/java/org/apache/flink/ml/common/datastream/DataStreamUtils.java:
##########
@@ -256,4 +325,79 @@ public void flatMap(T[] values, Collector<Tuple2<Integer,
T[]>> collector) {
}
}
}
+
+ /*
+ * A stream operator that takes a randomly sampled subset of elements in a
bounded data stream.
+ */
+ private static class SamplingOperator<T> extends AbstractStreamOperator<T>
+ implements OneInputStreamOperator<T, T>, BoundedOneInput {
+ private final int numSamples;
+
+ private final Random random;
+
+ private ListState<T> samplesState;
+
+ private List<T> samples;
+
+ private ListState<Integer> countState;
+
+ private int count;
+
+ SamplingOperator(int numSamples, long randomSeed) {
+ this.numSamples = numSamples;
+ this.random = new Random(randomSeed);
+ }
+
+ @Override
+ public void initializeState(StateInitializationContext context) throws
Exception {
+ super.initializeState(context);
+
+ ListStateDescriptor<T> samplesDescriptor =
+ new ListStateDescriptor<>(
+ "samplesState",
+ getOperatorConfig()
+ .getTypeSerializerIn(0,
getClass().getClassLoader()));
+ samplesState =
context.getOperatorStateStore().getListState(samplesDescriptor);
+ samples = new ArrayList<>(numSamples);
+ samplesState.get().forEach(samples::add);
+
+ ListStateDescriptor<Integer> countDescriptor =
+ new ListStateDescriptor<>("countState",
IntSerializer.INSTANCE);
+ countState =
context.getOperatorStateStore().getListState(countDescriptor);
+ Iterator<Integer> countIterator = countState.get().iterator();
+ if (countIterator.hasNext()) {
+ count = countIterator.next();
+ } else {
+ count = 0;
+ }
+ }
+
+ @Override
+ public void snapshotState(StateSnapshotContext context) throws
Exception {
+ super.snapshotState(context);
+ samplesState.update(samples);
+ countState.update(Collections.singletonList(count));
+ }
+
+ @Override
+ public void processElement(StreamRecord<T> streamRecord) throws
Exception {
+ T value = streamRecord.getValue();
+ count++;
+
+ if (samples.size() < numSamples) {
+ samples.add(value);
+ } else {
+ if (random.nextInt(count) < numSamples) {
Review Comment:
nits: could we re-use `random.nextInt(count)` for simplicity?
--
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]