Skip to content

Instantly share code, notes, and snippets.

@fbricon
Last active November 29, 2022 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fbricon/171faa1394e99d8011f2c8961de121d8 to your computer and use it in GitHub Desktop.
Save fbricon/171faa1394e99d8011f2c8961de121d8 to your computer and use it in GitHub Desktop.
Java TensorFlow example using JBang. Based on https://www.tensorflow.org/jvm/install. Doesn't run on Mac M1 (https://github.com/tensorflow/java/issues/252)
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS org.tensorflow:tensorflow-core-platform:0.4.2
//JAVA 11+
import org.tensorflow.ConcreteFunction;
import org.tensorflow.Signature;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;
import org.tensorflow.op.Ops;
import org.tensorflow.op.core.Placeholder;
import org.tensorflow.op.math.Add;
import org.tensorflow.types.TInt32;
public class HelloTensorFlow {
public static void main(String[] args) throws Exception {
System.out.println("Hello TensorFlow " + TensorFlow.version());
try (ConcreteFunction dbl = ConcreteFunction.create(HelloTensorFlow::dbl);
TInt32 x = TInt32.scalarOf(10);
Tensor dblX = dbl.call(x)) {
System.out.println(x.getInt() + " doubled is " + ((TInt32) dblX).getInt());
}
}
private static Signature dbl(Ops tf) {
Placeholder<TInt32> x = tf.placeholder(TInt32.class);
Add<TInt32> dblX = tf.math.add(x, x);
return Signature.builder().input("x", x).output("dbl", dblX).build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment