Machine Learning in TypeScript: Overview of ML Libraries in 2024
TypeScript is confidently carving out a niche not only in web development but also in Data Science. Thanks to static typing and compatibility with JavaScript, it becomes a convenient tool for building machine learning (ML) models that run directly in the browser or on the server (Node.js). In this article, we will review the key libraries for machine learning in TypeScript, their features, code examples, and use cases.
1. TensorFlow.js — The Main ML Framework for the Browser
TensorFlow.js is a port of the popular TensorFlow framework to JavaScript/TypeScript. It allows running model training and inference both in the browser and in Node.js. The library supports GPU acceleration via WebGL and WebGPU, providing a performance boost.
Key Features:
- Creating neural networks using a high-level API (tf.sequential, tf.model).
- Loading pre-trained models from TensorFlow Hub.
- Converting models from the Python version of TensorFlow to .json format.
- Working with tensors, optimizers, and layers.
Example: Linear Regression in TypeScript
import * as tf from '@tensorflow/tfjs';
// Data: relationship y = 2x - 1const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);
// Create modelconst model = tf.sequential();model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// Compilemodel.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
// Trainmodel.fit(xs, ys, {epochs: 250}).then(() => { model.predict(tf.tensor2d([10], [1, 1])).print(); // Output: ~19 (close to 2*10 - 1 = 19)});2. ML5.js — A Library for Creative ML
ML5.js is built on top of TensorFlow.js and is focused on ease of use. It provides ready-made models for image, sound, text, and gesture recognition. It is ideal for educational projects and prototyping.
Example: Image Classification
import * as ml5 from 'ml5';
// Load pre-trained MobileNet modelconst classifier = ml5.imageClassifier('MobileNet');
// Classify imageconst img = document.getElementById('myImage') as HTMLImageElement;classifier.classify(img, (err: Error | null, results: any[]) => { if (err) console.error(err); else console.log('Result:', results[0].label);});3. Brain.js — Neural Networks for Node.js and the Browser
Brain.js is a lightweight library for building neural networks in JavaScript/TypeScript. It supports various architectures: LSTM, RNN, GRU. It is well-suited for time series forecasting and text processing tasks.
Example: Simple Neural Network for XOR
import 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] }]);
const output = net.run([1, 0]); // ~0.99console.log(output);4. Synaptic — An Architecturally Flexible Library
Synaptic allows you to create neural networks of any architecture, including multilayer perceptrons, recurrent networks, and self-organizing Kohonen maps. It has no dependencies and works in the browser.
Example: Creating a Perceptron
import { Architect, Trainer } from 'synaptic';
const network = new Architect.Perceptron(2, 3, 1);const trainer = new Trainer(network);
trainer.train([ { input: [0, 0], output: [0] }, { input: [0, 1], output: [1] }, { input: [1, 0], output: [1] }, { input: [1, 1], output: [0] }], { iterations: 1000 });
console.log(network.activate([1, 0])); // ~0.98