
Introduction
When I think about AIML, I’m amazed at how smart it is at answering questions today. It can predict, suggest, classify, correct mistakes, and even generate content for you. A few years ago, technology wasn’t powerful enough to create things like we have today, such as generating images from text, predicting the future, and self-driving cars.
Before this framework, running AIML in a browser or server with JavaScript wasn’t possible. But now, using TensorFlow.js, we can use AI models anywhere JavaScript runs.
Having AIML skills can make your profile stand out in the web development industry. Since this framework was launched, the Python-only chain has been broken. Now, you can also use JavaScript to train AI models. Many web developers wonder how to train an AI model, what factors they should know, and if they need to learn extra things. Don’t worry, we’ll cover some important concepts for training AI models using JavaScript and provide an example to give you a clear idea.
Because there are very few guides available online, I decided to share some related knowledge about AIML using TensorFlow.js with you. Let’s get started.
Note:
Check out my earlier article on creating AIML models. In that article, I mainly covered definitions, types of machine learning, tensors, and the ideas we used in AIML with JavaScript.
https://webredo.net/article/build-your-first-ai-model-in-the-browser-using-tensorflowjs
IN THIS ARTICLE
1. Prepare a data?
2. How does a tensor take in data?
3. What methods are used to train a model?
4. Code.
5. How does it function?
Prepare Data
We are going to train model for linear regression problem where we play with Supervised Learning. (xs, ys) Before training any AI model, you should have a clear structure for your data. For simplicity, let’s consider an example of website page visits.
An AI model (of website page visits) can be useful for predicting tomorrow’s or next week’s visits, detecting unusual spikes, and suggesting the best time to post content if it’s a content site.
for simplicity lets consider - two data points pages & visits. for pages we use numbering like [1,2,3...].
Home - 1
About - 2
Contact - 3
Privacy - 4
Terms & conditions - 5
..etcHow does a tensor take in data?
Lets Build a tensor
const xs = tf.tensor([1,2,3,4,5]);But In practice, we won’t be restricted to just one layer of data. For instance, if we want to add a data point like the day with a webpage to gain more detailed insights into our website, we can use multiple inputs. Let’s see how.
Dataset
Instead of using fake data, we will look at a practical way to implement it. We will focus on the live training model approach.
For each view we can collect -
{
"page": 3, // page number
"day": 4, // week day
"visits": 1
} Caution - Numbering for pages and day should not change. If your page numbers are random, the model will learn noise
If you are Training mode is live You do not need to store this data in database. But will have to make sure parameter meaning should not change i.e if you are using 1 for home page then it should consistent for surety of output.
Both scenario is Possible Like
Storing entires in DB (Database) and training model with that Data
Train model with live events on website.
Most of the developers are known about the first steps where they can store entires in DB. So I will pick second scenerio i.e training model with live events.
Note
we will store model on our server using node.js.
Code
Alway initiate or load the model before feeding data. This process should start once your node.js server get started.
It will load the model into memory and will be available for operations.
import * as tf from "@tensorflow/tfjs-node";
import fs from "fs";
const MODEL_DIR = "./model";
let model;
async function loadModel() {
if (fs.existsSync(`${MODEL_DIR}/model.json`)) {
model = await tf.loadLayersModel(`file://${MODEL_DIR}/model.json`);
} else {
model = tf.sequential();
model.add(tf.layers.dense({ inputShape: [2], units: 8, activation: "relu" }));
model.add(tf.layers.dense({ units: 1 }));
model.compile({ optimizer: tf.train.adam(0.01), loss: "meanSquaredError" });
}
}
await loadModel();This above process will initial model or Create if not exist. All training data (like weights) will be storing at -file://${MODEL_DIR}/model.json folder. (You can define your folder path)
API request
app.post("/api/live-train", async (req, res) => {
try {
const { page, day, visits } = req.body;
// convert to tensor
const xs = tf.tensor2d([[page, day]]);
const ys = tf.tensor1d([visits]);
// train small & fast
await model.fit(xs, ys, { epochs: 20, verbose: 0 });
// save updated model
await model.save(`file://${MODEL_DIR}`);
tf.dispose([xs, ys]);
res.json({ ok: true, trainedWith: { page, day, visits } });
} catch (err) {
res.status(500).json({ error: err.message });
}
});Note
If you are using multiple models then make sure names are uniques. otherwise model get replaced. So use different names for each model type.
Code Explanation
// convert to tensor
const xs = tf.tensor2d([[page, day]]);
const ys = tf.tensor1d([visits]);Here we convert our raw input data into tensors because TensorFlow.js models can only learn from tensors, not raw numbers.
xs and ys are input-output pair so for 2 inputs features its tensor2d and for 1 its tensor1d
Example - For Home page (1) and Monday (1) visits are 10
const xs = tf.tensor2d([[1, 1]]);
const ys = tf.tensor1d([10]);Training model
await model.fit(xs, ys, { epochs: 20, verbose: 0 });Here we start training model. epochs define how many times we are teaching to the model so for 20 we are teaching model 20 time. we can use more number line 100 or 200 so that model can learn better from given data pattern.
verbose is use to hide the output logs because TensorFlow.js normally prints things like loss values, iteration steps, training progress. These logs can spam your server console on every request. So its better to hide unwanted responses and keep server clean.
// save updated model
await model.save(`file://${MODEL_DIR}`);
tf.dispose([xs, ys]);Once training is completed you can save model on same directory that you are using. Also make sure you remove the tensors from memory after saving for avoiding unwanted consumption.
res.json({ ok: true, trainedWith: { page, day, visits } }); This is only for informing client - browser that process is sussucssfull completed just like we do in our apis.
Yesss.!. Now our model is ready..
app.post("/api/predict", async (req, res) => {
const { page, day } = req.body;
const input = tf.tensor2d([[page, day]]);
const result = model.predict(input).dataSync()[0];
tf.dispose([input]);
res.json({ prediction: Math.round(result) });
});Onwards you can use this model for predicting future views on any page as per data you feed to the model.
It’s important to remember that you can’t ask for information that the model hasn’t been trained on. For example, if the model is trained on pages numbered 1 to 5, and you ask for page 6, the model will still give an answer, but it might not be as accurate. Neural networks can interpolate and extrapolate, which means they can learn from patterns and make guesses for new inputs, even if they haven’t seen them before in training.
Important
As we discussed earlier, AI models cannot be used for calculating data; they are for predicting or classifying based on the data you provide. For example, if you asked for my total visits last month, AI cannot answer this question. For these types of queries, a database is the only source that contains your real-time data, and you can get exact answers for such queries.
For more information you can visit Official TensorFlow website.
Now it’s your turn. Go ahead and train your own model for your needs. It’s a great time for web developers to use AI in websites to make them more engaging and dynamic. Thanks for reading this article. For daily updates, subscribe to our newsletter.
LOADING...

