How to Build Machine Learning Apps Directly in the Browser with JavaScript
This article explains a four‑level methodology for choosing JavaScript‑based machine‑learning tools, demonstrates practical code examples ranging from NLP with nlp.js to deep‑learning with TensorFlow.js, traditional ML with mljs, and statistical computing with stdlib, and shows how to run them entirely in the browser.
Atwood's law states that any application that can be implemented in JavaScript will eventually be rewritten in JavaScript. While Python dominates server‑side machine learning, the client side—especially browsers, mobile mini‑programs, and offline scenarios—relies on JavaScript frameworks.
Choosing a machine‑learning tool follows a four‑level hierarchy.
Level 1: Domain‑specific frameworks
These directly address tasks such as computer vision, NLP, or recommendation. For example, nlp.js can be used as follows:
const { NlpManager } = require('node-nlp');
const manager = new NlpManager({ languages: ['en'], forceNER: true });
manager.addDocument('en', 'goodbye for now', 'greetings.bye');
manager.addDocument('en', 'bye bye take care', 'greetings.bye');
manager.addAnswer('en', 'greetings.bye', 'Till next time');
(async () => {
await manager.train();
manager.save();
const response = await manager.process('en', 'I should go now');
console.log(response);
})();Install with: npm install node-nlp Training converges quickly, e.g.:
Epoch 1 loss 0.4629 time 1ms
Epoch 2 loss 0.2819 time 0ms
...
Epoch 31 loss 0.000046 time 0msThe resulting JSON includes intent, confidence, and entity extraction.
Level 2: Deep‑learning frameworks
TensorFlow.js remains the dominant deep‑learning library for the browser. A simple example loads the library and creates a tensor:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
</head>
<body>
<div id="tf-display"></div>
<script>
let a = tf.tensor1d([1.0]);
document.getElementById('tf-display').innerText = a;
</script>
</body>
</html>Other examples include reinforcement‑learning demos that store intermediate results in localStorage or IndexedDB, and Microsoft’s WebGL/Wasm‑based models.
Level 3: Traditional machine‑learning libraries
For tasks where classic algorithms suffice, libraries such as mljs provide k‑means clustering:
const kmeans = require('ml-kmeans');
let data = [[1,1,1],[1,2,1],[-1,-1,-1],[-1,-1,-1.5]];
let centers = [[1,2,1],[-1,-1,-1]];
let ans = kmeans(data, 2, { initialization: centers });
console.log(ans);Install with: npm i ml-kmeans Result shows cluster assignments and centroids.
k‑Nearest‑Neighbors can be demonstrated in the browser using ml:
<!DOCTYPE html>
<html>
<head>
<script src="https://www.lactame.com/lib/ml/4.0.0/ml.min.js"></script>
</head>
<body>
<div id="ml-display"></div>
<script>
const train_dataset = [[0,0,0],[0,1,1],[1,1,0],[2,2,2],[1,2,2],[2,1,2]];
const train_labels = [0,0,0,1,1,1];
let knn = new ML.KNN(train_dataset, train_labels, {k:2});
const test_dataset = [[0.9,0.9,0.9],[1.1,1.1,1.1],[1.1,1.1,1.2],[1.2,1.2,1.2]];
let ans = knn.predict(test_dataset);
document.getElementById('ml-display').innerText = ans;
</script>
</body>
</html>A decision‑tree example uses ml-cart with the Iris dataset.
const irisDataset = require('ml-dataset-iris');
const DecisionTreeClassifier = require('ml-cart');
const trainingSet = irisDataset.getNumbers();
const predictions = irisDataset.getClasses().map(c => irisDataset.getDistinctClasses().indexOf(c));
const options = { gainFunction: 'gini', maxDepth: 10, minNumSamples: 3 };
const classifier = new DecisionTreeClassifier.DecisionTreeClassifier(options);
classifier.train(trainingSet, predictions);
const result = classifier.predict(trainingSet);
console.log(result);Level 4: Mathematics and statistics libraries
Statistical computing is essential for data‑driven insight. The @stdlib library offers over 150 math functions and 35 distributions. Install with: npm install @stdlib/stdlib Example of a normal distribution:
const Normal = require('@stdlib/stats/base/dists/normal').Normal;
let dist1 = new Normal(0, 1);
console.log(dist1);
console.log(dist1.mean);
console.log(dist1.variance);It also provides datasets such as US state capitals:
const capitals = require('@stdlib/datasets/us-states-capitals');
console.log(capitals());Overall, for a project from zero to one, prioritize Level 1 tools for rapid deployment; for incremental or complex growth, Levels 3 and 4 give deeper data understanding.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Taobao Frontend Technology
The frontend landscape is constantly evolving, with rapid innovations across familiar languages. Like us, your understanding of the frontend is continually refreshed. Join us on Taobao, a vibrant, all‑encompassing platform, to uncover limitless potential.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
