Skip to content

Instantly share code, notes, and snippets.

@NatuMyers
Last active December 10, 2020 15:23
Show Gist options
  • Save NatuMyers/a55cef9193095ce5485893ee7ca6ffab to your computer and use it in GitHub Desktop.
Save NatuMyers/a55cef9193095ce5485893ee7ca6ffab to your computer and use it in GitHub Desktop.
Tensorflow.js Linear Regression
<html>
<head>
<title>Tensor Flow</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.6.1"></script>
<script>
const nr_epochs=2048; // higher=better but slower
var tfinterface;
const model = tf.sequential();
function initTF() {
// 1. TRAINING DATA - learn this 10x table
const xs = tf.tensor2d([1,2,3,4,5], [5,1]);
const ys = tf.tensor2d([10,20,30,40,50], [5,1]);
// 2. ML MODEL - linear regression model
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// Prep for training
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// train -- the higher the number the more accurate you'll get (but longer run time)
tfinterface=model.fit(xs,ys,{epochs: nr_epochs});
}
// 3. WRAPPER AROUND PREDICT
function predict(n) {
return tfinterface.then(()=> { return model.predict(tf.tensor2d([n],[1,1])); });
}
// Helper for form
function formpredict(v,r) {
predict(v).then(function(res) {
// alert(res.get([0]));
r.innerHTML=res.get([0]);
});
}
</script>
</head>
<!-- HTML -->
<body onLoad='initTF();'>
<p>
<div id='res'>Wait</div>
<p>
<form name='iForm' onSubmit='formpredict(this.val.value,document.getElementById("res")); return false;')>
<script>
document.getElementById("res").innerHTML="&nbsp;";
</script>
Input Number: <input name='val'><input type=submit>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment