JavaScript for Machine Learning: Capabilities and Limitations in Practice
\n\nMany developers are accustomed to thinking that machine learning is the prerogative of Python. Indeed, the Python ecosystem with TensorFlow, PyTorch, and Scikit-learn libraries dominates this field. However, JavaScript (especially in the Node.js environment) also offers interesting tools for ML. In this article, we will explore what can be done with JavaScript, where its real boundaries lie, and how to use available libraries in practice.
\n\nWhy JavaScript for ML? Main Scenarios
\n\nThe main advantage of JavaScript is its versatility. If your team already writes in JS and you don't have the resources to learn Python, you can implement simple ML models directly in Node.js. The main use cases are:
\n\n- \n
- Browser-based machine learning — running models directly on the client (e.g., TensorFlow.js in the browser). This is ideal for tasks with sensitive data (medicine, finance). \n
- Server-side solutions — Node.js handles simple predictions, text classification, or sentiment analysis well. \n
- Prototyping and learning — for quick experiments and proof of concept demonstrations. \n
- Integration with the web ecosystem — if your project is already on Node.js, there's no need to spin up a separate Python microservice. \n
Practical Example: Number Classification with Brain.js
\n\nBrain.js is one of the simplest libraries for neural networks in JavaScript. It doesn't require a GPU and is well-suited for training on a CPU. Let's look at an example of recognizing handwritten digits (a simplified version of MNIST).
\n\nFirst, install the library:
\nnpm install brain.js\n\nNow let's write code to train a neural network to recognize digits 0 and 1 based on 4x4 pixel binary images:
\n\nconst brain = require('brain.js');\n\n// Create a neural network with one hidden layer\nconst net = new brain.NeuralNetwork({ hiddenLayers: [3] });\n\n// Training data: 16 inputs (4x4), 1 output (0 or 1)\nconst trainingData = [\n { input: [0,0,0,0, 0,1,1,0, 0,1,1,0, 0,0,0,0], output: [0] }, // digit 0\n { input: [0,0,0,0, 0,0,1,0, 0,0,1,0, 0,0,0,0], output: [1] }, // digit 1\n { input: [0,0,0,0, 1,1,1,0, 0,1,1,0, 0,0,0,0], output: [0] }, // another 0\n { input: [0,0,0,0, 0,0,1,0, 0,1,1,0, 0,0,0,0], output: [1] } // another 1\n];\n\n// Train the network\nnet.train(trainingData, {\n iterations: 2000,\n errorThresh: 0.005,\n log: true,\n logPeriod: 500\n});\n\n// Test\nconst testData = [0,0,0,0, 0,1,1,0, 0,1,1,0, 0,0,0,0]; // looks like 0\nconst result = net.run(testData);\nconsole.log(`Result: ${result[0] > 0.5 ? '1' : '0'} (confidence: ${result[0].toFixed(3)})`);\n\nThis example shows how quickly you can train a simple network. However, for real MNIST recognition, a deeper architecture and thousands of examples would be required.
\n\nTensorFlow.js: A Powerful Tool for Node.js
\n\nTensorFlow.js is a port of the popular framework to JavaScript. It supports both the browser and Node.js. Here's an example of linear regression for predicting real estate prices (simplified):
\n\nconst tf = require('@tensorflow/tfjs-node');\n\n// Data: area (sq.m) -> price ($)\nconst xs = tf.tensor2d([50, 60, 70, 80, 90], [5, 1]);\nconst ys = tf.tensor2d([150000, 180000, 210000, 240000, 270000], [5, 1]);\n\n// Create a model\nconst model = tf.sequential();\nmodel.add(tf.layers.dense({ units: 1, inputShape: [1] }));\n\n// Compile\nmodel.compile({ optimizer: 'sgd', loss: 'meanSquaredError' });\n\n// Train\nasync function train() {\n await model.fit(xs, ys, { epochs: 100 });\n \n // Prediction for a 75 sq.m house\n const prediction = model.predict(tf.tensor2d([75], [1, 1]));\n prediction.print(); // ~225000\n}\n\ntrain();\n\nTensorFlow.js provides access to most