or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# TensorFlow Java API

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: libtensorflow_jni

7

- **Package Type**: maven

8

- **Language**: Java

9

- **Installation**: Maven dependency `org.tensorflow:tensorflow:1.15.0`

10

11

## Core Imports

12

13

```java

14

import org.tensorflow.*;

15

```

16

17

For specific classes:

18

19

```java

20

import org.tensorflow.Graph;

21

import org.tensorflow.Session;

22

import org.tensorflow.Tensor;

23

import org.tensorflow.TensorFlow;

24

import org.tensorflow.DataType;

25

```

26

27

## Basic Usage

28

29

```java

30

import org.tensorflow.*;

31

32

public class TensorFlowExample {

33

public static void main(String[] args) {

34

// Check TensorFlow version

35

System.out.println("TensorFlow version: " + TensorFlow.version());

36

37

// Create a simple computation graph: y = 3 * x

38

try (Graph graph = new Graph()) {

39

// Create operations

40

Output<Float> x = graph.opBuilder("Placeholder", "x")

41

.setAttr("dtype", DataType.FLOAT)

42

.build()

43

.output(0);

44

45

Output<Float> three = graph.opBuilder("Const", "three")

46

.setAttr("dtype", DataType.FLOAT)

47

.setAttr("value", Tensor.create(3.0f))

48

.build()

49

.output(0);

50

51

Output<Float> y = graph.opBuilder("Mul", "y")

52

.addInput(x)

53

.addInput(three)

54

.build()

55

.output(0);

56

57

// Execute the graph

58

try (Session session = new Session(graph)) {

59

try (Tensor<Float> inputTensor = Tensor.create(2.0f);

60

Tensor<Float> result = session.runner()

61

.feed("x", inputTensor)

62

.fetch("y")

63

.run()

64

.get(0)

65

.expect(Float.class)) {

66

67

System.out.println("Result: " + result.floatValue()); // Prints: 6.0

68

}

69

}

70

}

71

}

72

}

73

```

74

75

## Architecture

76

77

The TensorFlow Java API is built around several key components:

78

79

- **Graph**: Represents a computational graph with operations and data flow

80

- **Session**: Execution environment for running operations in a graph

81

- **Tensor**: Multi-dimensional arrays that flow through the graph

82

- **Operation**: Individual computation nodes in the graph

83

- **Native Layer**: JNI bridge to TensorFlow's C++ core implementation

84

85

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

86

87

## Capabilities

88

89

### Core Framework

90

91

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

92

93

```java { .api }

94

public final class TensorFlow {

95

public static native String version();

96

public static native byte[] registeredOpList();

97

public static byte[] loadLibrary(String filename);

98

}

99

100

public final class Graph implements ExecutionEnvironment, AutoCloseable {

101

public Graph();

102

public OperationBuilder opBuilder(String type, String name);

103

public Operation operation(String name);

104

public Iterator<Operation> operations();

105

public void close();

106

}

107

108

public final class Session implements AutoCloseable {

109

public Session(Graph graph);

110

public Session(Graph graph, ConfigProto config);

111

public Runner runner();

112

public void close();

113

114

public interface Runner {

115

Runner feed(String operationName, Tensor<?> t);

116

Runner feed(Output<?> output, Tensor<?> t);

117

Runner fetch(String operationName);

118

Runner fetch(Output<?> output);

119

Runner addTarget(String operationName);

120

Runner addTarget(Operation operation);

121

List<Tensor<?>> run();

122

}

123

}

124

```

125

126

### Tensor Operations

127

128

Multi-dimensional array operations for data manipulation and computation.

129

130

```java { .api }

131

public final class Tensor<T> implements AutoCloseable {

132

public static <T> Tensor<T> create(Object obj);

133

public static <T> Tensor<T> create(Class<T> type, long[] shape, ByteBuffer data);

134

135

public DataType dataType();

136

public int numDimensions();

137

public long numElements();

138

public long[] shape();

139

public void copyTo(Object dst);

140

public Object copyTo(Object dst, int offset, int length);

141

142

// Type-specific value accessors

143

public float floatValue();

144

public double doubleValue();

145

public int intValue();

146

public long longValue();

147

public boolean booleanValue();

148

public byte[] bytesValue();

149

150

public void close();

151

}

152

153

public final class Tensors {

154

public static Tensor<String> create(String data);

155

public static Tensor<String> create(String[] data);

156

public static Tensor<Float> create(float data);

157

public static Tensor<Float> create(float[] data);

158

public static Tensor<Float> create(float[][] data);

159

public static Tensor<Double> create(double data);

160

public static Tensor<Double> create(double[] data);

161

public static Tensor<Integer> create(int data);

162

public static Tensor<Integer> create(int[] data);

163

public static Tensor<Long> create(long data);

164

public static Tensor<Long> create(long[] data);

165

public static Tensor<Boolean> create(boolean data);

166

public static Tensor<Boolean> create(boolean[] data);

167

}

168

```

169

170

### Data Types and Shapes

171

172

Type system and shape utilities for tensor operations.

173

174

```java { .api }

175

public enum DataType {

176

FLOAT(1), DOUBLE(2), INT32(3), UINT8(4), INT16(5),

177

INT8(6), STRING(7), COMPLEX64(8), INT64(9), BOOL(10),

178

QINT8(11), QUINT8(12), QINT32(13), BFLOAT16(14),

179

QINT16(15), QUINT16(16), UINT16(17), COMPLEX128(18),

180

HALF(19), RESOURCE(20), VARIANT(21), UINT32(22), UINT64(23);

181

182

public int value();

183

public static DataType fromValue(int value);

184

}

185

186

public final class Shape {

187

public static Shape scalar();

188

public static Shape vector(long size);

189

public static Shape matrix(long numRows, long numColumns);

190

public static Shape make(long firstDimensionSize, long... otherDimensionSizes);

191

192

public int numDimensions();

193

public long size(int dimensionIndex);

194

public long numElements();

195

public boolean hasUnknownDimension();

196

}

197

```

198

199

### Operations and Graph Building

200

201

Graph construction and operation management functionality.

202

203

```java { .api }

204

public final class Operation {

205

public String name();

206

public String type();

207

public int numOutputs();

208

public Output<?> output(int idx);

209

public OutputSpec outputSpec(int idx);

210

211

public static final class OutputSpec {

212

public String name();

213

public DataType dataType();

214

public Shape shape();

215

}

216

}

217

218

public final class OperationBuilder {

219

public Operation build();

220

public OperationBuilder addInput(Output<?> input);

221

public OperationBuilder addInputList(Output<?>[] inputs);

222

public OperationBuilder addControlInput(Operation control);

223

public OperationBuilder setDevice(String device);

224

225

// Attribute setters

226

public OperationBuilder setAttr(String name, String value);

227

public OperationBuilder setAttr(String name, String[] value);

228

public OperationBuilder setAttr(String name, byte[] value);

229

public OperationBuilder setAttr(String name, long value);

230

public OperationBuilder setAttr(String name, long[] value);

231

public OperationBuilder setAttr(String name, float value);

232

public OperationBuilder setAttr(String name, float[] value);

233

public OperationBuilder setAttr(String name, boolean value);

234

public OperationBuilder setAttr(String name, boolean[] value);

235

public OperationBuilder setAttr(String name, DataType value);

236

public OperationBuilder setAttr(String name, DataType[] value);

237

public OperationBuilder setAttr(String name, Tensor<?> value);

238

public OperationBuilder setAttr(String name, Tensor<?>[] value);

239

public OperationBuilder setAttr(String name, Shape value);

240

public OperationBuilder setAttr(String name, Shape[] value);

241

}

242

243

public final class Output<T> implements Operand<T> {

244

public Operation op();

245

public int index();

246

public DataType dataType();

247

public Shape shape();

248

}

249

```

250

251

### Saved Models

252

253

Loading and executing pre-trained TensorFlow models.

254

255

```java { .api }

256

public final class SavedModelBundle implements AutoCloseable {

257

public static SavedModelBundle load(String exportDir, String... tags);

258

public static SavedModelBundle load(String exportDir, String[] tags, ConfigProto config);

259

260

public Session session();

261

public Graph graph();

262

public byte[] metaGraphDef();

263

public void close();

264

}

265

```

266

267

### Error Handling

268

269

Exception types for TensorFlow operations.

270

271

```java { .api }

272

public final class TensorFlowException extends RuntimeException {

273

public TensorFlowException(String message);

274

public TensorFlowException(String message, Throwable cause);

275

}

276

```

277

278

## Configuration

279

280

### Session Configuration

281

282

```java

283

// Create session with configuration

284

ConfigProto config = ConfigProto.newBuilder()

285

.setAllowSoftPlacement(true)

286

.setLogDevicePlacement(false)

287

.build();

288

289

try (Session session = new Session(graph, config)) {

290

// Use configured session

291

}

292

```

293

294

### GPU Configuration

295

296

```java

297

// Configure GPU memory growth

298

ConfigProto config = ConfigProto.newBuilder()

299

.setGpuOptions(GPUOptions.newBuilder()

300

.setAllowGrowth(true)

301

.build())

302

.build();

303

```

304

305

## Memory Management

306

307

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

308

309

```java

310

// Use try-with-resources for automatic cleanup

311

try (Graph graph = new Graph();

312

Session session = new Session(graph);

313

Tensor<Float> input = Tensor.create(1.0f)) {

314

315

// Use resources

316

317

} // Resources automatically closed

318

```

319

320

## Thread Safety

321

322

- `Graph` instances are thread-safe

323

- `Session` instances are thread-safe

324

- `Tensor` instances are **NOT** thread-safe

325

- `Operation` instances are thread-safe

326

327

## Version Compatibility

328

329

- **Java Version**: Requires Java 7 or higher

330

- **Platform Support**: Linux, macOS, Windows (x86_64)

331

- **TensorFlow Version**: 1.15.0

332

- **Native Dependencies**: Automatically managed via JNI

333

334

## Installation

335

336

### Maven

337

338

```xml

339

<dependency>

340

<groupId>org.tensorflow</groupId>

341

<artifactId>tensorflow</artifactId>

342

<version>1.15.0</version>

343

</dependency>

344

```

345

346

### Gradle

347

348

```gradle

349

dependencies {

350

implementation 'org.tensorflow:tensorflow:1.15.0'

351

}

352

```

353

354

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.