Chapter 18: MLBrain.js
Brain.js (often written as brain.js), a super popular JavaScript library for Machine Learning and neural networks.
I think when you wrote “MLBrain.js”, you meant Brain.js — it’s one of the most beginner-friendly tools for doing ML right in JavaScript (browser or Node.js). No typos — it’s exactly what fits your pattern of questions about ML in JS!
I’m explaining it like your favorite teacher: clear, detailed, with real examples, analogies, code you can copy-paste, and why it’s still loved in 2026 even with bigger players like TensorFlow.js around.
Step 1: What Exactly is Brain.js?
Brain.js is an open-source JavaScript library that lets you create, train, and run neural networks (simple to medium-sized) directly in the browser or on Node.js servers.
Key highlights (2026 reality):
- GPU accelerated — uses your computer’s graphics card for faster training (falls back to normal JS if no GPU).
- Super simple API — hides all scary math (backpropagation, gradients, matrices) so beginners can focus on ideas.
- Multiple network types — feedforward (basic), recurrent (sequences like text/time), LSTM/GRU, even convolutional basics.
- Runs everywhere — browser (no server needed!), Node.js, or even mobile web.
- Export/import models — save trained network as JSON → load anywhere.
Official site: brain.js.org GitHub: github.com/BrainJS/brain.js (still active with community maintenance).
It’s not as powerful as TensorFlow.js or PyTorch for huge models, but it’s perfect for:
- Learning ML concepts
- Small/medium projects
- Browser-based demos (no backend)
- Fun experiments (color prediction, text generation basics)
Step 2: Why Use Brain.js in 2026?
- Easiest entry to neural nets in JS — 10–20 lines for a working model.
- No heavy dependencies — lightweight (~100–200 KB minified).
- Privacy-friendly — train/use models entirely client-side (data never leaves browser).
- Great for teaching — W3Schools, YouTube tutorials, colleges still use it.
- GPU fallback — fast on modern laptops/phones with WebGL.
Compared to others:
- vs TensorFlow.js → Brain.js is simpler, less features, but faster to prototype.
- vs ml5.js → Brain.js more low-level (you control network), ml5.js higher-level/fun.
Step 3: Classic Beginner Example – Color Contrast Predictor
One of the most famous Brain.js demos: train a network to predict if text color should be black or white on a background color (for readability).
Real use: auto-suggest text color for buttons/websites.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<!DOCTYPE html> <html> <head> <title>Brain.js Color Contrast Example</title> <script src="https://cdn.jsdelivr.net/npm/brain.js@2"></script> <style> body { font-family: Arial; text-align: center; padding: 50px; } #result { font-size: 2em; margin: 20px; padding: 20px; border: 2px solid; } </style> </head> <body> <h1>Brain.js: Black or White Text?</h1> <input type="color" id="colorPicker" value="#ff0000"> <button onclick="predict()">Predict Text Color</button> <div id="result">Pick a background color!</div> <script> // Create neural network const net = new brain.NeuralNetwork({ hiddenLayers: [3], // one hidden layer with 3 neurons }); // Training data: RGB input → black(0) or white(1) output const trainingData = [ { input: { r: 0, g: 0, b: 0 }, output: { white: 1 } }, // black bg → white text { input: { r: 1, g: 1, b: 1 }, output: { black: 1 } }, // white bg → black text { input: { r: 0.5, g: 0, b: 0 }, output: { white: 1 } }, // dark red → white { input: { r: 1, g: 0.8, b: 0.8 }, output: { black: 1 } }, // light pink → black // ... add 100+ more examples for better accuracy (real projects use more) ]; // Train! net.train(trainingData, { iterations: 20000, // how many times to see data log: true, // print progress logPeriod: 1000, learningRate: 0.3 }); console.log("Training complete! Ready to predict."); function predict() { const hex = document.getElementById('colorPicker').value; const r = parseInt(hex.slice(1,3), 16)/255; const g = parseInt(hex.slice(3,5), 16)/255; const b = parseInt(hex.slice(5,7), 16)/255; const result = net.run({ r, g, b }); const textColor = result.white > result.black ? 'white' : 'black'; const confidence = Math.max(result.white, result.black).toFixed(2); const div = document.getElementById('result'); div.style.backgroundColor = hex; div.style.color = textColor; div.innerHTML = `Predicted: {textColor.toUpperCase()} text<br>Confidence: ${confidence}`; } </script> </body> </html> |
Save as HTML → open in browser → pick colors → watch it predict!
- Dark backgrounds → suggests white text
- Light backgrounds → black text
- Learns from examples (you can add more for better accuracy)
Step 4: Another Fun Example – XOR Gate (Classic Neural Net Test)
Brain.js can learn non-linear things like XOR (single perceptron can’t!).
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
const net = new brain.NeuralNetwork(); const data = [ { input: [0, 0], output: [0] }, { input: [0, 1], output: [1] }, { input: [1, 0], output: [1] }, { input: [1, 1], output: [0] } ]; net.train(data, { iterations: 100000 }); console.log(net.run([0, 0])); // ~ [0] console.log(net.run([0, 1])); // ~ [1] console.log(net.run([1, 0])); // ~ [1] console.log(net.run([1, 1])); // ~ [0] |
It learns the XOR pattern perfectly!
Step 5: Quick Summary Table (Keep Handy!)
| Feature | Brain.js Details (2026) | Why It Matters for Beginners |
|---|---|---|
| Ease of Use | new brain.NeuralNetwork() + .train() + .run() | 5–10 lines to start |
| GPU Support | Automatic via gpu.js | 5–10× faster on laptops with graphics card |
| Network Types | Feedforward, RNN, LSTM, GRU, etc. | Try different for text/time-series/images |
| Data Format | Simple JS objects/arrays | No tensors needed |
| Export Model | net.toJSON() / net.fromJSON() | Save & share trained models |
| Best For | Learning, prototypes, browser demos | Not huge production models (use TF.js then) |
Final Teacher Advice
Brain.js = your first friend for neural networks in JavaScript. It’s simple, fun, educational — perfect after you learn basic ML concepts (perceptrons, training/testing). In 2026 it’s still used in tutorials, small web apps, interactive demos, and teaching (W3Schools has a whole page!).
Once comfortable → move to TensorFlow.js for bigger things.
Got it? 🔥
Questions?
- Want code for text sentiment or number prediction?
- How to train on your own data?
- Brain.js vs TensorFlow.js comparison?
Just ask — next lesson ready! 🚀
