@Test
public void should_test_then_train() throws InterruptedException {
// Start local cluster
LocalCluster cluster = new LocalCluster();
LocalDRPC localDRPC = new LocalDRPC();
try {
TridentTopology toppology = new TridentTopology();
MemoryMapState.Factory evaluationStateFactory = new MemoryMapState.Factory();
MemoryMapState.Factory perceptronModelStateFactory = new MemoryMapState.Factory();
TridentState perceptronModel = toppology.newStaticState(perceptronModelStateFactory);
TridentState perceptronEvaluation = toppology.newStaticState(evaluationStateFactory);
// Predict
Stream predictionStream = toppology.newStream("nandsamples", new NANDSpout()) //
.stateQuery(perceptronModel, new Fields("instance"), new ClassifyQuery<Boolean>("perceptron"), new Fields("prediction"));
// Update evaluation
predictionStream //
.persistentAggregate(evaluationStateFactory, new Fields("instance", "prediction"), new AccuracyAggregator<Boolean>(), new Fields("accuracy"));
// Update model
predictionStream.partitionPersist(perceptronModelStateFactory, new Fields("instance"), new ClassifierUpdater<Boolean>("perceptron", new PerceptronClassifier()));
// Classification stream
toppology.newDRPCStream("predict", localDRPC)
// convert DRPC args to instance
.each(new Fields("args"), new DRPCArgsToInstance(), new Fields("instance"))
// Query classifier to classify instance
.stateQuery(perceptronModel, new Fields("instance"), new ClassifyQuery<Boolean>("perceptron"), new Fields("prediction")).project(new Fields("prediction"));
// Evaluation stream
toppology.newDRPCStream("evaluate", localDRPC) //
.stateQuery(perceptronEvaluation, new EvaluationQuery<Boolean>(), new Fields("eval")) //
.project(new Fields("eval"));
cluster.submitTopology(this.getClass().getSimpleName(), new Config(), toppology.build());
Thread.sleep(4000);
assertEquals(Boolean.TRUE, extractPrediction(localDRPC.execute("predict", "1.0 0.0 0.0")));
assertEquals(Boolean.TRUE, extractPrediction(localDRPC.execute("predict", "1.0 0.0 1.0")));
assertEquals(Boolean.TRUE, extractPrediction(localDRPC.execute("predict", "1.0 1.0 0.0")));
assertEquals(Boolean.FALSE, extractPrediction(localDRPC.execute("predict", "1.0 1.0 1.0")));
Double evaluation = extractEvaluation(localDRPC.execute("evaluate", ""));
assertTrue(evaluation > 0.9);
assertTrue(evaluation < 1);
} finally {
cluster.shutdown();
localDRPC.shutdown();
}
}