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.jscan be used as follows:
<code>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);
})();
</code>Install with:
<code>npm install node-nlp</code>Training converges quickly, e.g.:
<code>Epoch 1 loss 0.4629 time 1ms
Epoch 2 loss 0.2819 time 0ms
...
Epoch 31 loss 0.000046 time 0ms</code>The 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:
<code><!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>
</code>Other examples include reinforcement‑learning demos that store intermediate results in
localStorageor
IndexedDB, and Microsoft’s WebGL/Wasm‑based models.
Level 3: Traditional machine‑learning libraries
For tasks where classic algorithms suffice, libraries such as
mljsprovide k‑means clustering:
<code>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);
</code>Install with:
<code>npm i ml-kmeans</code>Result shows cluster assignments and centroids.
k‑Nearest‑Neighbors can be demonstrated in the browser using
ml:
<code><!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>
</code>A decision‑tree example uses
ml-cartwith the Iris dataset.
<code>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);
</code>Level 4: Mathematics and statistics libraries
Statistical computing is essential for data‑driven insight. The
@stdliblibrary offers over 150 math functions and 35 distributions. Install with:
<code>npm install @stdlib/stdlib</code>Example of a normal distribution:
<code>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);
</code>It also provides datasets such as US state capitals:
<code>const capitals = require('@stdlib/datasets/us-states-capitals');
console.log(capitals());
</code>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.
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.