Loading lesson path
Concept visual
Start from A
TesorFlow.js
Machine Learning. For different Machine Learning tasks you must combine different types of Layers into a Model that can be trained with data to predict future values. TensorFlow.js is supporting different types of
Layers.
Layers.
A Tensorflow project has this typical workflow:
Suppose you knew a function that defined a strait line:
Formula
Y = 1.2X + 5
Then you could calculate any y value with the JavaScript formula:y = 1.2 * x + 5;To demonstrate Tensorflow.js, we could train a Tensorflow.js model to predict Y values based on X inputs.
The TensorFlow model does not know the function.
// Create Training Data const xs = tf.tensor([0, 1, 2, 3, 4]);
const ys = xs.mul(1.2).add(5);
// Define a Linear Regression Model const model = tf.sequential();
model.add(tf.layers.dense({units:1, inputShape:[1]}));
// Specify Loss and Optimizer model.compile({loss:'meanSquaredError', optimizer:'sgd'});
// Train the Model model.fit(xs, ys, {epochs:500}).then(() => {myFunction()});
// Use the Model function myFunction() {
const xMax = 10;
const xArr = [];
const yArr = [];
for (let x = 0; x <= xMax; x++) {
let result = model.predict(tf.tensor([Number(x)]));
result.data().then(y => {
xArr.push(x);
yArr.push(Number(y));
if (x == xMax) {plot(xArr, yArr)};
});
}
}Create a tensor (xs) with 5 x values:
const xs = tf.tensor([0, 1, 2, 3, 4]);
Create a tensor (ys) with 5 correct y answers (multiply xs with 1.2 and add 5):
const ys = xs.mul(1.2).add(5);Create a sequential mode:.
const model = tf.sequential();