JavaScript for Machine Learning: Practical Tools and Code Examples
In the first part, we discussed why JavaScript can be useful in machine learning. Now let's move on to practice. If you are studying programming and want to try ML without switching to Python — this article is for you. We will look at real libraries, write code in Node.js, and discuss where JS is truly convenient. The material is suitable even for JavaScript for beginners.
Libraries for ML in JavaScript
The JavaScript ecosystem is actively developing. Here are the key tools for working with data and models:
- TensorFlow.js — a port of the well-known framework from Google. It allows you to train models directly in the browser or on Node.js.
- Brain.js — a simple library for neural networks. Ideal for learning basic concepts.
- ml.js — a set of utilities for regression, clustering, and classification.
- Natural — a library for natural language processing (NLP).
Let's look at an example with TensorFlow.js. Installation via npm:
npm install @tensorflow/tfjsNow let's write a simple linear regression:
const tf = require('@tensorflow/tfjs');
// Create a modelconst model = tf.sequential();model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// Compilemodel.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// Data: 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]);
// Trainingmodel.fit(xs, ys, {epochs: 250}).then(() => { // Prediction model.predict(tf.tensor2d([5], [1, 1])).print();});The result will be close to 9 (since 2*5 - 1 = 9). This example shows how easy it is to start training a model in JavaScript.
Limitations of JavaScript in ML
Despite its convenience, there are important limitations:
- Performance: JS is inferior to Python in numerical calculations. TensorFlow.js uses WebGL, but complex models run slower.
- Ecosystem: There are fewer libraries for ML than in Python. There are no analogs of PyTorch or scikit-learn.
- Community: Most examples and solutions are in Python. It is harder to find ready-made pipelines for JS.
- Resources: Node.js is not optimized for working with GPU (although there are experimental solutions).
However, for small projects, prototyping, and web applications, JS is quite suitable. Especially if you already know JavaScript and don't want to learn a new language.
Practical example: text classification on Node.js
Let's use the Natural library to determine the sentiment of a review. This is useful for chatbots or comment analysis.
Installation:
npm install naturalClassifier code:
const natural = require('natural');const classifier = new natural.BayesClassifier();
// Train on examplesclassifier.addDocument('excellent product', 'positive');classifier.addDocument('terrible quality', 'negative');classifier.addDocument('okay, but expensive', 'neutral');
classifier.train();
// Testconsole.log(classifier.classify('very bad')); // negativeconsole.log(classifier.getClassifications('super thing'));This example shows how JavaScript handles NLP tasks. For programming such solutions, deep knowledge of mathematics is not required — the library does everything itself.
When should you choose JavaScript for ML?
Here are scenarios where JS is justified:
- Web applications: The model wor