Machine Learning in TypeScript: Top Libraries for ML in 2024

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Machine Learning in TypeScript: Overview of Libraries and Tools



TypeScript is not just strict typing for JavaScript. Thanks to its ecosystem and compatibility with JS, it is becoming a powerful platform for machine learning (ML) directly in the browser or on the server (Node.js). In this article, we will cover four key libraries that allow you to develop, train, and run ML models in TypeScript.



1. TensorFlow.js — The ML Flagship in TypeScript

TensorFlow.js is a port of the popular TensorFlow framework to JavaScript/TypeScript. It supports both the browser and Node.js. The main advantage is the ability to perform training and inference directly on the client side without sending data to the server.



Installation

npm install @tensorflow/tfjsnpm install @tensorflow/tfjs-node  // for Node.js with CPU accelerationnpm install @tensorflow/tfjs-node-gpu // for GPU


Example: Linear Regression in TypeScript

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

// Create a simple model: y = 2x - 1const model = tf.sequential();model.add(tf.layers.dense({ units: 1, inputShape: [1] }));

// Compilationmodel.compile({ optimizer: 'sgd', loss: 'meanSquaredError' });

// Training dataconst xs = tf.tensor2d([0, 1, 2, 3, 4], [5, 1]);const ys = tf.tensor2d([-1, 1, 3, 5, 7], [5, 1]);

// Trainingmodel.fit(xs, ys, { epochs: 250 }).then(() => { // Prediction for x=5 const output = model.predict(tf.tensor2d([5], [1, 1])) as tf.Tensor; output.print(); // ≈ 9 (2*5 - 1)});


TensorFlow.js also supports loading pre-trained models (e.g., MobileNet for image classification) and working with computation graphs.



2. ML5.js — ML for Creative Projects

ML5.js is built on top of TensorFlow.js and is focused on ease of use. It is ideal for artists, designers, and ML beginners. The library provides high-level APIs for tasks such as classification, text generation, gesture recognition, etc.



Installation

npm install ml5


Example: Image Classification (MobileNet)

import * as ml5 from 'ml5';

// Load the pre-trained MobileNet modelconst classifier = ml5.imageClassifier('MobileNet');

// Classify an image by URLconst img = new Image();img.crossOrigin = 'anonymous';img.src = 'https://example.com/cat.jpg';

img.onload = () => { classifier.classify(img, (err: Error | null, results: any[]) => { if (err) { console.error(err); return; } console.log('Results:', results); // [{ label: 'tabby cat', confidence: 0.98 }, ...] });};


ML5.js automatically loads the model weights and provides a simple callback. It is great for quick prototypes and interactive installations.



3. Brain.js — Neural Networks Without Complexity

Brain.js is a library for creating neural networks with minimal code. It supports feedforward networks, LSTM, and RNN. It works both in the browser and in Node.js.



Installation

npm install brain.js


Example: XOR Function (Exclusive OR)

import * as brain from 'brain.js';

const net = new brain.NeuralNetwork();

net.train([ { input: [0, 0], output: [0] }, { input: [0, 1], output: [1] }, { input: [1, 0], output: [1] }, { input: [1, 1], output: [0] }], { iterations: 10000, errorThresh: 0.005});

const output = net.run([1, 0]); // ≈ 0.98 (close to 1)console.log(`Result: ${output}`);


Brain.js automatically normalizes data and supports saving/loading a trained model in JSON.



4. Synaptic — Architectural Flexibility

Synaptic is a library for creating complex neural network architectures: perceptrons, multilayer networks

Recommendations