Welcome to the TensorFlow Basics tutorial. This guide will walk you through installing TensorFlow.js, creating simple tensors, building a neural network, and running it directly in the browser.
TensorFlow.js can be included via a CDN. Add the following script tag to your HTML head:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.15.0/dist/tf.min.js"></script>
Creating and printing a tensor:
const a = tf.tensor([1, 2, 3, 4]);
a.print();
This example fits a line y = 2x - 1
using gradient descent.
async function runLinearModel() {
// Training data
const xs = tf.tensor1d([0, 1, 2, 3, 4]);
const ys = tf.tensor1d([ -1, 1, 3, 5, 7]); // y = 2x -1
// Define a simple sequential model
const model = tf.sequential();
model.add(tf.layers.dense({units:1, inputShape:[1]}));
// Compile with optimizer & loss
model.compile({optimizer:'sgd', loss:'meanSquaredError'});
// Train
await model.fit(xs, ys, {epochs:200, verbose:0});
// Predict
const preds = model.predict(tf.tensor1d([5,6]));
const predVals = await preds.data();
return predVals;
}
runLinearModel().then(vals => {
document.getElementById('out-1').textContent =
'Predictions for x=5,6 => [' + vals.map(v=>v.toFixed(2)).join(', ') + ']';
});
The model learns the relationship between x
and y
. After training, it predicts values close to the true line (e.g., for x=5
the true y
is 9
).