TensorFlow.js lets you run machine learning directly in your web browser. This means you can use AI without installing anything extra.
TensorFlow.js for browser
import * as tf from '@tensorflow/tfjs'; async function loadModel() { // Load a pre-trained model const model = await tf.loadLayersModel('model_url/model.json'); // Prepare input data as a tensor const input = tf.tensor([[5.1, 3.5, 1.4, 0.2]]); // Make prediction const prediction = model.predict(input); // Get prediction values prediction.print(); } loadModel();
Use tf.loadLayersModel() to load models saved in TensorFlow.js format.
Input data must be converted to tensors before prediction.
const tensor = tf.tensor([1, 2, 3, 4]); tensor.print();
async function predict() { const model = await tf.loadLayersModel('https://example.com/model.json'); const input = tf.tensor2d([[0.5, 0.1]]); const output = model.predict(input); output.print(); } predict();
async function trainAndPredict() { const model = tf.sequential(); model.add(tf.layers.dense({units: 1, inputShape: [2]})); model.compile({optimizer: 'sgd', loss: 'meanSquaredError'}); const xs = tf.tensor2d([[1, 2], [3, 4]], [2, 2]); const ys = tf.tensor2d([[1], [3]], [2, 1]); await model.fit(xs, ys, {epochs: 5}); const prediction = model.predict(tf.tensor2d([[5, 6]], [1, 2])); prediction.print(); } trainAndPredict();
This code builds a simple model that learns the rule y = 2x - 1. It trains on four points, then predicts y for x=5.
import * as tf from '@tensorflow/tfjs'; async function run() { // Create a simple model const model = tf.sequential(); model.add(tf.layers.dense({units: 1, inputShape: [1]})); model.compile({optimizer: 'sgd', loss: 'meanSquaredError'}); // Training data: y = 2x - 1 const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]); const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]); // Train the model await model.fit(xs, ys, {epochs: 10}); // Predict for a new value const output = model.predict(tf.tensor2d([5], [1, 1])); output.print(); } run();
TensorFlow.js runs all computations on the user's device, so performance depends on their hardware.
Always convert your input data into tensors before using the model.
You can save and load models in the browser using local storage or URLs.
TensorFlow.js lets you run and train machine learning models directly in the browser.
You prepare data as tensors and use models to make predictions or learn from data.
This approach makes AI accessible without extra software or servers.
Practice
TensorFlow.js in a web browser?Solution
Step 1: Understand TensorFlow.js purpose
TensorFlow.js is designed to run and train ML models directly in the browser environment.Step 2: Compare options
Options A, B, and C mention installing software, server-only use, or separate apps, which are not true for TensorFlow.js.Final Answer:
Run and train machine learning models directly in the browser without extra software -> Option CQuick Check:
TensorFlow.js runs ML in browser = D [OK]
- Thinking TensorFlow.js needs server or software install
- Confusing browser use with server-side ML
- Assuming extra apps are required
Solution
Step 1: Recall TensorFlow.js tensor creation syntax
The correct method to create a 1D tensor with values istf.tensor([1, 2, 3]).Step 2: Check other options for syntax errors
tf.tensor1d(1, 2, 3) uses wrong function and arguments, A and D have invalid array syntax.Final Answer:
tf.tensor([1, 2, 3]) -> Option DQuick Check:
Correct tensor syntax = C [OK]
- Using semicolons or spaces instead of commas in arrays
- Wrong function name or arguments
- Missing array brackets
const t = tf.tensor([1, 2, 3, 4]); const result = t.square().arraySync(); console.log(result);
Solution
Step 1: Understand the code operations
The tensortcontains [1, 2, 3, 4]. Thesquare()method squares each element.Step 2: Calculate squared values and output
Squaring each element: 1²=1, 2²=4, 3²=9, 4²=16. ThearraySync()converts tensor to JS array.Final Answer:
[1, 4, 9, 16] -> Option AQuick Check:
Tensor square() output = A [OK]
- Confusing square() with identity (no change)
- Expecting sum instead of element-wise operation
- Thinking square() is not a valid method
const t = tf.tensor([1, 2, 3]); const reshaped = t.reshape([2, 2]); console.log(reshaped.arraySync());
Solution
Step 1: Check tensor size and reshape target shape
The tensor has 3 elements, but reshape tries to make shape [2, 2] which needs 4 elements.Step 2: Understand reshape requirements
Reshape must keep total elements same. Here 3 != 4, so it causes an error.Final Answer:
The reshape size [2, 2] does not match the number of elements in tensor -> Option BQuick Check:
Reshape size must match elements = A [OK]
- Ignoring total element count mismatch
- Thinking arraySync() is invalid
- Believing reshape needs 1D array argument
y from x. Which sequence of steps is correct to train the model in the browser?Solution
Step 1: Understand model training workflow in TensorFlow.js
First, define the model architecture with layers, then compile it specifying optimizer and loss function.Step 2: Prepare input and output data as tensors and call model.fit()
Training requires data tensors for inputs (x) and outputs (y), then callmodel.fit()to train the model in the browser.Final Answer:
Define model layers, compile with optimizer and loss, prepare tensors for x and y, then call model.fit() with data -> Option AQuick Check:
Model training steps = B [OK]
- Skipping compile before training
- Trying to predict without training
- Manually setting weights without training
- Assuming training must happen on server
Ready to prove it?
Pass the test and this pattern moves unknown
