Skip to content

Instantly share code, notes, and snippets.

@kerminz
Last active September 20, 2018 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerminz/c5681ebb4b8af4cfa5dfc819ff92ae5a to your computer and use it in GitHub Desktop.
Save kerminz/c5681ebb4b8af4cfa5dfc819ff92ae5a to your computer and use it in GitHub Desktop.
Tensorflow.js example from blogpost on kerm.in
const trainX = [10.90, 30.60, 50.70, 25.10, 7.80, 42.50, 35.20, 40.40, 25.30, 12.30, 60.20, 47.80, 45.70, 27.50, 15.10, 20.10, 47.50, 32.50, 37.50, 20.00];
const trainY = [2.00, 3.00, 7.00, 2.00, 2.50, 6.00, 5.00, 4.00, 6.00, 1.00, 7.00, 5.50, 7.00, 4.50, 1.50, 4.00, 9.00, 3.00, 6.50, 2.50];
const m = tf.variable(tf.scalar(Math.random()));
const b = tf.variable(tf.scalar(Math.random()));
function predict(x) {
return tf.tidy(function() {
return m.mul(x).add(b);
});
}
function loss(prediction, actualValues) {
const error = prediction.sub(actualValues).square().mean();
return error;
}
const learningRate = 0.0003;
const optimizer = tf.train.sgd(learningRate);
function train() {
optimizer.minimize(function() {
const predsYs = predict(tf.tensor1d(trainX));
stepLoss = loss(predsYs, tf.tensor1d(trainY))
stepLoss.print();
return stepLoss;
});
}
for (var i=0; i < 1000; i++) {
train();
}
predict(23.50).print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment