Skip to content

Instantly share code, notes, and snippets.

@curiousily
Created June 20, 2018 17:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curiousily/2a8fb08d0e20961256f5a88cb7b8e10d to your computer and use it in GitHub Desktop.
Save curiousily/2a8fb08d0e20961256f5a88cb7b8e10d to your computer and use it in GitHub Desktop.
Create a Simple Linear Regression model in TensorFlow.js that given some number from the Fibonacci sequence predicts the next one while only running in the browser!
// What is a Tensor?
const myFirstTensor = tf.scalar(42)
console.log(myFirstTensor)
myFirstTensor.print()
const oneDimTensor = tf.tensor1d([1, 2, 3])
oneDimTensor.print()
// Preparing the training data
function fibonacci(num){
var a = 1, b = 0, temp;
var seq = []
while (num > 0){
temp = a;
a = a + b;
b = temp;
seq.push(b)
num--;
}
return seq;
}
const fibs = fibonacci(100)
const xs = tf.tensor1d(fibs.slice(0, fibs.length - 1))
const ys = tf.tensor1d(fibs.slice(1))
const xmin = xs.min();
const xmax = xs.max();
const xrange = xmax.sub(xmin);
function norm(x) {
return x.sub(xmin).div(xrange);
}
xsNorm = norm(xs)
ysNorm = norm(ys)
// Building our model
const a = tf.variable(tf.scalar(Math.random()))
const b = tf.variable(tf.scalar(Math.random()))
a.print()
b.print()
function predict(x) {
return tf.tidy(() => {
return a.mul(x).add(b)
});
}
// Training
function loss(predictions, labels) {
return predictions.sub(labels).square().mean();
}
const learningRate = 0.5;
const optimizer = tf.train.sgd(learningRate);
const numIterations = 10000;
const errors = []
for (let iter = 0; iter < numIterations; iter++) {
optimizer.minimize(() => {
const predsYs = predict(xsNorm);
const e = loss(predsYs, ysNorm);
errors.push(e.dataSync())
return e
});
}
// Making predictions
console.log(errors[0])
console.log(errors[numIterations - 1])
xTest = tf.tensor1d([2, 354224848179262000000])
predict(xTest).print()
a.print()
b.print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment