use of com.spotify.featran.java.JFeatureSpec in project zoltar by spotify.
the class TensorFlowGraphModelTest method testModelInference.
@Test
public void testModelInference() throws Exception {
final Path graphFile = createADummyTFGraph();
final JFeatureSpec<Double> featureSpec = JFeatureSpec.<Double>create().required(d -> d, Identity.apply("feature"));
final URI settingsUri = getClass().getResource("/settings_dummy.json").toURI();
final String settings = new String(Files.readAllBytes(Paths.get(settingsUri)), StandardCharsets.UTF_8);
final ModelLoader<TensorFlowGraphModel> tfModel = TensorFlowGraphLoader.create(graphFile.toString(), null, null);
final PredictFn<TensorFlowGraphModel, Double, double[], Double> predictFn = (model, vectors) -> vectors.stream().map(vector -> {
try (Tensor<Double> input = Tensors.create(vector.value()[0])) {
List<Tensor<?>> results = null;
try {
results = model.instance().runner().fetch(mulResult).feed(inputOpName, input).run();
return Prediction.create(vector.input(), results.get(0).doubleValue());
} finally {
if (results != null) {
results.forEach(Tensor::close);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
final ExtractFn<Double, double[]> extractFn = FeatranExtractFns.doubles(featureSpec, settings);
final Double[] input = new Double[] { 0.0D, 1.0D, 7.0D };
final double[] expected = Arrays.stream(input).mapToDouble(d -> d * 2.0D).toArray();
final CompletableFuture<double[]> result = PredictorsTest.newBuilder(tfModel, extractFn, predictFn).predictor().predict(input).thenApply(predictions -> {
return predictions.stream().mapToDouble(Prediction::value).toArray();
}).toCompletableFuture();
assertArrayEquals(result.get(), expected, Double.MIN_VALUE);
}
Aggregations