Skip to content

Instantly share code, notes, and snippets.

Last active December 10, 2020 15:23
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Tensorflow.js Linear Regression
<title>Tensor Flow</title>
<script src=""></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),ys,{epochs: nr_epochs});
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]));
<!-- HTML -->
<body onLoad='initTF();'>
<div id='res'>Wait</div>
<form name='iForm' onSubmit='formpredict(this.val.value,document.getElementById("res")); return false;')>
Input Number: <input name='val'><input type=submit>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment