or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

callbacks.mdimage-processing.mdindex.mdio.mdsavedmodel.mdtensorboard.md
tile.json

tessl/npm-tensorflow--tfjs-node

TensorFlow backend for TensorFlow.js via Node.js - provides native TensorFlow execution in backend JavaScript applications under the Node.js runtime, accelerated by the TensorFlow C binary under the hood

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@tensorflow/tfjs-node@4.22.x

To install, run

npx @tessl/cli install tessl/npm-tensorflow--tfjs-node@4.22.0

index.mddocs/

TensorFlow.js Node

TensorFlow.js Node provides a native TensorFlow backend for Node.js applications, enabling high-performance machine learning operations using the full power of the native TensorFlow C++ library. It extends the browser-based TensorFlow.js API with Node.js-specific functionality including native tensor operations, file system model loading, image processing, and TensorBoard integration.

Package Information

  • Package Name: @tensorflow/tfjs-node
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @tensorflow/tfjs-node

Core Imports

ESM (TypeScript/Modern JavaScript):

import * as tf from '@tensorflow/tfjs-node';

CommonJS:

const tf = require('@tensorflow/tfjs-node');

For specific functionality:

// Main TensorFlow.js functionality
import { tensor, sequential, layers } from '@tensorflow/tfjs-node';

// Node-specific functionality
import { node, io, version } from '@tensorflow/tfjs-node';

Basic Usage

import * as tf from '@tensorflow/tfjs-node';

// Create tensors and perform operations
const a = tf.tensor([[1, 2], [3, 4]]);
const b = tf.tensor([[5, 6], [7, 8]]);
const result = tf.matMul(a, b);

console.log('Matrix multiplication result:');
result.print();

// Create and train a model
const model = tf.sequential({
  layers: [
    tf.layers.dense({ inputShape: [2], units: 3, activation: 'relu' }),
    tf.layers.dense({ units: 1, activation: 'linear' })
  ]
});

model.compile({ optimizer: 'adam', loss: 'meanSquaredError' });

// Train with sample data
const xs = tf.tensor2d([[1, 2], [2, 3], [3, 4], [4, 5]]);
const ys = tf.tensor2d([[3], [5], [7], [9]]);

model.fit(xs, ys, { epochs: 100 }).then(() => {
  console.log('Model trained');
});

Architecture

TensorFlow.js Node is built around several key components:

  • Core TensorFlow.js API: Complete tensor operations, models, layers, optimizers, losses, and metrics from the browser version
  • Native Backend: High-performance tensor operations using the TensorFlow C++ library
  • Node.js Extensions: File system access, HTTP loading, image processing, and server-specific functionality
  • Model Persistence: Enhanced save/load capabilities using the file system
  • Training Tools: Progress callbacks and TensorBoard integration for training visualization

Capabilities

Core TensorFlow.js API

All standard TensorFlow.js functionality including tensor operations, neural networks, and machine learning algorithms. This provides the same API as the browser version but with native performance.

// Core tensor operations (examples)
function tensor(values: TensorLike, shape?: Shape, dtype?: DataType): Tensor;
function matMul(a: Tensor, b: Tensor, transposeA?: boolean, transposeB?: boolean): Tensor;
function sequential(config?: SequentialArgs): Sequential;

// Model creation and layers
const layers: {
  dense: (args: DenseLayerArgs) => Dense;
  conv2d: (args: Conv2DLayerArgs) => Conv2D;
  // ... hundreds of other operations and layers
};

Note: Complete TensorFlow.js API documentation is available at https://js.tensorflow.org/api/latest/

Node-specific Image Processing

Decode and encode images directly to/from tensors using native implementations for optimal performance.

namespace node {
  function decodeImage(contents: Uint8Array, channels?: number, dtype?: string, expandAnimations?: boolean): Tensor3D | Tensor4D;
  function decodeJpeg(contents: Uint8Array, channels?: number, ratio?: number, fancyUpscaling?: boolean, tryRecoverTruncated?: boolean, acceptableFraction?: number, dctMethod?: string): Tensor3D;
  function decodePng(contents: Uint8Array, channels?: number, dtype?: string): Tensor3D;
  function decodeBmp(contents: Uint8Array, channels?: number): Tensor3D;
  function decodeGif(contents: Uint8Array): Tensor4D;
  function encodeJpeg(image: Tensor3D, format?: ImageFormat, quality?: number, progressive?: boolean, optimizeSize?: boolean, chromaDownsampling?: boolean, densityUnit?: DensityUnit, xDensity?: number, yDensity?: number, xmpMetadata?: string): Promise<Uint8Array>;
  function encodePng(image: Tensor3D, compression?: number): Promise<Uint8Array>;
}

type ImageFormat = '' | 'grayscale' | 'rgb';
type DensityUnit = 'in' | 'cm';

Image Processing

SavedModel Support

Load and run inference with TensorFlow SavedModels, enabling integration with models trained in Python TensorFlow.

namespace node {
  function loadSavedModel(path: string, tags?: string[], signature?: string): Promise<TFSavedModel>;
  function getMetaGraphsFromSavedModel(path: string): Promise<MetaGraph[]>;
  function getNumOfSavedModels(): number;
}

interface TFSavedModel extends InferenceModel {
  inputs: ModelTensorInfo;
  outputs: ModelTensorInfo;
  predict(inputs: Tensor | Tensor[] | NamedTensorMap, config?: PredictConfig): Tensor | Tensor[] | NamedTensorMap;
  dispose(): void;
}

SavedModel Support

File System and HTTP Loading

Enhanced model loading and saving capabilities using the Node.js file system and HTTP requests.

// Extended io namespace with Node.js capabilities
const io: {
  // All browser tf.io functionality plus:
  fileSystem: (path: string | string[]) => IOHandler;
  nodeHTTPRequest: (path: string, requestInit?: RequestInit, weightPathPrefix?: string) => IOHandler;
};

File System and HTTP IO

TensorBoard Integration

Log training metrics and visualize model performance using TensorBoard integration.

namespace node {
  function tensorBoard(logdir?: string, args?: TensorBoardCallbackArgs): TensorBoardCallback;
  function summaryFileWriter(logdir: string, maxQueue?: number, flushMillis?: number, filenameSuffix?: string): SummaryFileWriter;
}

interface TensorBoardCallbackArgs {
  updateFreq?: 'batch' | 'epoch';
  histogramFreq?: number;
}

interface SummaryFileWriter {
  scalar(name: string, value: number, step: number, description?: string): void;
  histogram(name: string, data: Tensor, step: number, buckets?: number, description?: string): void;
  flush(): void;
}

TensorBoard Integration

Training Callbacks

Enhanced training experience with progress bars and logging callbacks.

class ProgbarLogger extends CustomCallback {
  constructor();
}

class TensorBoardCallback extends CustomCallback {
  constructor(logdir?: string, updateFreq?: 'batch' | 'epoch', histogramFreq?: number);
}

Training Callbacks

Version Information

const version: {
  [key: string]: string;
  'tfjs-node': string;
  'tfjs-core': string;
  'tfjs-data': string;
  'tfjs-layers': string;
  'tfjs-converter': string;
};

Common Types

// Tensor types
type TensorLike = TypedArray | number | boolean | string | RecursiveArray<number | boolean | string>;
type Shape = number[];
type DataType = 'float32' | 'int32' | 'bool' | 'complex64' | 'string';

// Model types
interface InferenceModel {
  inputs: ModelTensorInfo;
  outputs: ModelTensorInfo;
  predict(inputs: Tensor | Tensor[] | NamedTensorMap, config?: PredictConfig): Tensor | Tensor[] | NamedTensorMap;
  dispose(): void;
}

interface IOHandler {
  load?(): Promise<ModelArtifacts>;
  save?(modelArtifacts: ModelArtifacts): Promise<SaveResult>;
}

// SavedModel types
interface MetaGraph {
  tags: string[];
  signatureDef: {[key: string]: SignatureDefEntry};
}

interface ModelTensorInfo {
  [inputName: string]: {
    name: string;
    shape: number[];
    dtype: string;
  };
}