How to Use TensorFlow Using Java/JavaScript

How to Use TensorFlow Using Java/JavaScript

This article will help get experienced Java/JavaScript developers use machine learning/deep learning in the TensorFlow ecosystem without any prior knowledge of Python.


Nowadays, there is a great market for machine learning and deep learning enthusiasts, as it is a niche technology, but it also requires different programming skillset.

There are plenty of tools and libraries available for this like Numpy, Keras, and TensorFlow, but most of them play around R, MATLAB, and, of course, Python.

So, now the problem is reskilling the existing programmer community, which is typically trained on languages like C, C++, and Java.

You might also enjoy: Machine Learning In Node.js With TensorFlow.js


There is lots of misconception that TensorFlow is made only for Python and its allies. Don't worry, if you are an experienced Java/JS programmer and want to get your hands dirty with ML/DL, you still can!

The solution is TensorFlow for Java and TensorFlow.js.

Learn by Example


To start with Java, you need to first to set up a Maven project and add the following dependency to your pom.xml.


This is an enumeration of two libraries:

  • libtensorflow
  • libtensorflow_jni

This wraps the TensorFlow C++ library and JNI connector to access it through Java programs.

Additionally, you can add the following dependency to support GPU acceleration. By default, it works on CPU powers.


Now, you are all set to use TensorFlow features on Java. You can use following test program to check the environment.

import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;

public class HelloTF {
  public static void main(String[] args) throws Exception {
    try (Graph g = new Graph()) {
      final String value = "Hello from " + TensorFlow.version();

      // Construct the computation graph with a single operation, a constant
      // named "MyConst" with a value "value".
      try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
        // The Java API doesn't yet include convenience functions for adding operations.
        g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();

      // Execute the "MyConst" operation in a Session.
      try (Session s = new Session(g);
           Tensor output = s.runner().fetch("MyConst").run().get(0)) {
        System.out.println(new String(output.bytesValue(), "UTF-8"));

This is basically creating an operation graph with a const and assigning a value as the current version. For fetching it, you need to run it inside a session.


To start with JavaScript, you just need a single package available through CDN. It's available through an NPN package, as well, but it is easier to use CDN for working with a browser.

Add the below script tag to your HTML file.

<script src="[email protected]"> </script>

That's it. Now, you can test TensorFlow features like training, re-training, and converting existing models into JavaScript-compatible models right into your browser.

To test, you can use following code.

// Define a model for linear regression.
    const model = tf.sequential();
    model.add(tf.layers.dense({units: 1, inputShape: [1]}));

    // Prepare the model for training: Specify the loss and the optimizer.
    model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

    // Generate some synthetic data for training.
    const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
    const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

    // Train the model using the data., ys).then(() => {
        // Use the model to do inference on a data point the model hasn't seen before:
        result = model.predict(tf.tensor2d([5], [1, 1]));

This is a basic linear regression model trained with mean square error and gradient descent.

You can have a look at a complete example on GitHub.

tensorflow java javascript

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Java vs. JavaScript: Know The Difference

Java vs. JavaScript: Know the Difference, Java vs. JavaScript: What's the Difference? Java vs. JavaScript: Major Similarities and Differences. pros and cons of JavaScript and Java.

Java vs JavaScript: Difference between Java and JavaScript

The video on Java vs JavaScript provides you with a short and crisp description of the two programming languages. You will also see the head to head comparison between the two on various aspects and learn the similarities and differences between them.

Java Core (2020) | Java for beginners | Brush up your Java Skills | Get Hired

In this video we will learn about all the major concepts that come under Java Core . The course is very carefully designed and is made with keeping simplicit...

JavaScript != Java

Lately I've been doing a lot of work with Java and JavaScript through JavaScript Engine and every time I come to a question about the two someone feels the need to answer the question with,&nbsp;<em>"Java and JavaScript are two different languages. They have nothing in common!"</em>&nbsp;or&nbsp;<em>"Just because the word Java is in JavaScript doesn't mean its Java"</em>&nbsp;or&nbsp;<em>"Java != JavaScript"</em>.

TensorFlow for JavaScript

TensorFlow for JavaScript. TensorFlow.js is the recently-released JavaScript version of TensorFlow that runs in the browser and Node.js