or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/maven-org-tensorflow--tensorflow

Complete Java API for TensorFlow machine learning and deep neural networks

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.tensorflow/tensorflow@1.15.x

To install, run

npx @tessl/cli install tessl/maven-org-tensorflow--tensorflow@1.15.0

index.mddocs/

TensorFlow Java API

A comprehensive Java library for machine learning and deep neural networks using TensorFlow. This library provides the complete Java API for TensorFlow, enabling developers to build, train, and deploy machine learning models entirely in Java applications.

Package Information

  • Package Name: libtensorflow_jni
  • Package Type: maven
  • Language: Java
  • Installation: Maven dependency org.tensorflow:tensorflow:1.15.0

Core Imports

import org.tensorflow.*;

For specific classes:

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

Basic Usage

import org.tensorflow.*;

public class TensorFlowExample {
    public static void main(String[] args) {
        // Check TensorFlow version
        System.out.println("TensorFlow version: " + TensorFlow.version());
        
        // Create a simple computation graph: y = 3 * x
        try (Graph graph = new Graph()) {
            // Create operations
            Output<Float> x = graph.opBuilder("Placeholder", "x")
                .setAttr("dtype", DataType.FLOAT)
                .build()
                .output(0);
            
            Output<Float> three = graph.opBuilder("Const", "three")
                .setAttr("dtype", DataType.FLOAT)
                .setAttr("value", Tensor.create(3.0f))
                .build()
                .output(0);
            
            Output<Float> y = graph.opBuilder("Mul", "y")
                .addInput(x)
                .addInput(three)
                .build()
                .output(0);
            
            // Execute the graph
            try (Session session = new Session(graph)) {
                try (Tensor<Float> inputTensor = Tensor.create(2.0f);
                     Tensor<Float> result = session.runner()
                         .feed("x", inputTensor)
                         .fetch("y")
                         .run()
                         .get(0)
                         .expect(Float.class)) {
                    
                    System.out.println("Result: " + result.floatValue()); // Prints: 6.0
                }
            }
        }
    }
}

Architecture

The TensorFlow Java API is built around several key components:

  • Graph: Represents a computational graph with operations and data flow
  • Session: Execution environment for running operations in a graph
  • Tensor: Multi-dimensional arrays that flow through the graph
  • Operation: Individual computation nodes in the graph
  • Native Layer: JNI bridge to TensorFlow's C++ core implementation

The library automatically handles native library loading, memory management, and provides thread-safe execution environments for machine learning workloads.

Capabilities

Core Framework

Essential TensorFlow functionality including graph construction, session management, and tensor operations.

public final class TensorFlow {
    public static native String version();
    public static native byte[] registeredOpList();
    public static byte[] loadLibrary(String filename);
}

public final class Graph implements ExecutionEnvironment, AutoCloseable {
    public Graph();
    public OperationBuilder opBuilder(String type, String name);
    public Operation operation(String name);
    public Iterator<Operation> operations();
    public void close();
}

public final class Session implements AutoCloseable {
    public Session(Graph graph);
    public Session(Graph graph, ConfigProto config);
    public Runner runner();
    public void close();
    
    public interface Runner {
        Runner feed(String operationName, Tensor<?> t);
        Runner feed(Output<?> output, Tensor<?> t);
        Runner fetch(String operationName);
        Runner fetch(Output<?> output);
        Runner addTarget(String operationName);
        Runner addTarget(Operation operation);
        List<Tensor<?>> run();
    }
}

Tensor Operations

Multi-dimensional array operations for data manipulation and computation.

public final class Tensor<T> implements AutoCloseable {
    public static <T> Tensor<T> create(Object obj);
    public static <T> Tensor<T> create(Class<T> type, long[] shape, ByteBuffer data);
    
    public DataType dataType();
    public int numDimensions();
    public long numElements();
    public long[] shape();
    public void copyTo(Object dst);
    public Object copyTo(Object dst, int offset, int length);
    
    // Type-specific value accessors
    public float floatValue();
    public double doubleValue();
    public int intValue();
    public long longValue();
    public boolean booleanValue();
    public byte[] bytesValue();
    
    public void close();
}

public final class Tensors {
    public static Tensor<String> create(String data);
    public static Tensor<String> create(String[] data);
    public static Tensor<Float> create(float data);
    public static Tensor<Float> create(float[] data);
    public static Tensor<Float> create(float[][] data);
    public static Tensor<Double> create(double data);
    public static Tensor<Double> create(double[] data);
    public static Tensor<Integer> create(int data);
    public static Tensor<Integer> create(int[] data);
    public static Tensor<Long> create(long data);
    public static Tensor<Long> create(long[] data);
    public static Tensor<Boolean> create(boolean data);
    public static Tensor<Boolean> create(boolean[] data);
}

Data Types and Shapes

Type system and shape utilities for tensor operations.

public enum DataType {
    FLOAT(1), DOUBLE(2), INT32(3), UINT8(4), INT16(5), 
    INT8(6), STRING(7), COMPLEX64(8), INT64(9), BOOL(10), 
    QINT8(11), QUINT8(12), QINT32(13), BFLOAT16(14), 
    QINT16(15), QUINT16(16), UINT16(17), COMPLEX128(18), 
    HALF(19), RESOURCE(20), VARIANT(21), UINT32(22), UINT64(23);
    
    public int value();
    public static DataType fromValue(int value);
}

public final class Shape {
    public static Shape scalar();
    public static Shape vector(long size);
    public static Shape matrix(long numRows, long numColumns);
    public static Shape make(long firstDimensionSize, long... otherDimensionSizes);
    
    public int numDimensions();
    public long size(int dimensionIndex);
    public long numElements();
    public boolean hasUnknownDimension();
}

Operations and Graph Building

Graph construction and operation management functionality.

public final class Operation {
    public String name();
    public String type();
    public int numOutputs();
    public Output<?> output(int idx);
    public OutputSpec outputSpec(int idx);
    
    public static final class OutputSpec {
        public String name();
        public DataType dataType();
        public Shape shape();
    }
}

public final class OperationBuilder {
    public Operation build();
    public OperationBuilder addInput(Output<?> input);
    public OperationBuilder addInputList(Output<?>[] inputs);
    public OperationBuilder addControlInput(Operation control);
    public OperationBuilder setDevice(String device);
    
    // Attribute setters
    public OperationBuilder setAttr(String name, String value);
    public OperationBuilder setAttr(String name, String[] value);
    public OperationBuilder setAttr(String name, byte[] value);
    public OperationBuilder setAttr(String name, long value);
    public OperationBuilder setAttr(String name, long[] value);
    public OperationBuilder setAttr(String name, float value);
    public OperationBuilder setAttr(String name, float[] value);
    public OperationBuilder setAttr(String name, boolean value);
    public OperationBuilder setAttr(String name, boolean[] value);
    public OperationBuilder setAttr(String name, DataType value);
    public OperationBuilder setAttr(String name, DataType[] value);
    public OperationBuilder setAttr(String name, Tensor<?> value);
    public OperationBuilder setAttr(String name, Tensor<?>[] value);
    public OperationBuilder setAttr(String name, Shape value);
    public OperationBuilder setAttr(String name, Shape[] value);
}

public final class Output<T> implements Operand<T> {
    public Operation op();
    public int index();
    public DataType dataType();
    public Shape shape();
}

Saved Models

Loading and executing pre-trained TensorFlow models.

public final class SavedModelBundle implements AutoCloseable {
    public static SavedModelBundle load(String exportDir, String... tags);
    public static SavedModelBundle load(String exportDir, String[] tags, ConfigProto config);
    
    public Session session();
    public Graph graph();
    public byte[] metaGraphDef();
    public void close();
}

Error Handling

Exception types for TensorFlow operations.

public final class TensorFlowException extends RuntimeException {
    public TensorFlowException(String message);
    public TensorFlowException(String message, Throwable cause);
}

Configuration

Session Configuration

// Create session with configuration
ConfigProto config = ConfigProto.newBuilder()
    .setAllowSoftPlacement(true)
    .setLogDevicePlacement(false)
    .build();

try (Session session = new Session(graph, config)) {
    // Use configured session
}

GPU Configuration

// Configure GPU memory growth
ConfigProto config = ConfigProto.newBuilder()
    .setGpuOptions(GPUOptions.newBuilder()
        .setAllowGrowth(true)
        .build())
    .build();

Memory Management

All TensorFlow Java objects that implement AutoCloseable must be properly closed to prevent memory leaks:

// Use try-with-resources for automatic cleanup
try (Graph graph = new Graph();
     Session session = new Session(graph);
     Tensor<Float> input = Tensor.create(1.0f)) {
    
    // Use resources
    
} // Resources automatically closed

Thread Safety

  • Graph instances are thread-safe
  • Session instances are thread-safe
  • Tensor instances are NOT thread-safe
  • Operation instances are thread-safe

Version Compatibility

  • Java Version: Requires Java 7 or higher
  • Platform Support: Linux, macOS, Windows (x86_64)
  • TensorFlow Version: 1.15.0
  • Native Dependencies: Automatically managed via JNI

Installation

Maven

<dependency>
    <groupId>org.tensorflow</groupId>
    <artifactId>tensorflow</artifactId>
    <version>1.15.0</version>
</dependency>

Gradle

dependencies {
    implementation 'org.tensorflow:tensorflow:1.15.0'
}

The TensorFlow Java library automatically includes the native JNI library (libtensorflow_jni) as a transitive dependency, so no additional configuration is required for native library loading.