TensorFlow.js Tutorial: A Neuron Implementation for Linear Regression
Welcome to this TensorFlow.js tutorial where we will be implementing a neuron for linear regression using TensorFlow.js. TensorFlow.js is an open-source library that allows you to build, train, and deploy machine learning models in the browser or on Node.js.
Linear Regression
Linear regression is a simple but powerful technique used for predicting a continuous value based on one or more input features. In this tutorial, we will be implementing a neuron for linear regression which will learn the relationship between the input features and the target value.
Implementing a Neuron for Linear Regression
First, we need to import TensorFlow.js into our HTML file. You can do this by adding the following script tag:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
Next, let’s define our neuron for linear regression:
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
Now we can train our neuron using some sample data:
const xs = tf.tensor2d([1, 2, 3, 4, 5], [5, 1]);
const ys = tf.tensor2d([2, 4, 6, 8, 10], [5, 1]);
model.fit(xs, ys, {epochs: 100}).then(() => {
// Model training complete
});
Conclusion
Congratulations! You have successfully implemented a neuron for linear regression using TensorFlow.js. This is just the beginning of your journey into machine learning with TensorFlow.js. Feel free to experiment with different parameters and datasets to further improve your model.
Catch more episodes from Machine Learning for Web Developers (Web ML) → https://goo.gle/learn-WebML
Please give code because rewriting give many errors
Hey @JasonMayes firstly thank you for an exciting course thus far, challenging is an understatement but the small wins are making this a rewarding process. I am really stuck on this video, my model doesn't seem to be training correctly as when I run the evaluate function on the same tensor you gave your model [[750, 1]] I am not receiving whole numbers, sometimes they are negative and sometimes they are positive, I find the value is not really showing any correlation to the sample data and each time I refresh the page using the same evaluation tensor I am getting a completely random value. I feel like I cannot move to the next video till I figure this out, I have tried copying word for word your script and I have tried my own variations but am not making any progress. Hoping you can shed some light on what might be going on.
Could someone please explain, how model with single layer (2 inputs, 1 neuron) maps to the linear regression formula "Y = mX + b"? I guess "b" in this formula is bias, but the author didn't specified any bias when defining the model
Is it necessary to use shuffle: true when training the model if both inputs and outputs have been through shuffleCombo? Awesome content, by the way!