Linear Regression with Vanilla JavaScript
Machine learning is not a programming language. It's more about math. Programming languages are the tools.
Linear regression in machine learnning is the proceess to find the corresponding slope and y intercept. With the fundamental knowledege of some calculus one can code up some algorithm for linear regression with any programming language.
We want to find the parameters for x and y intercept with y =ax + b, where we set a =1 and b = 0. After every training cycle a and b will change until they fit the data most accuretly.
Playgroud
Add data:x:
y:
| x | y |
|---|
Learning Rate:
Training Speed: times per second.
Line Formula:
y = x
y = x
Mean Standard Error:
//define line function f = a*x + b
var a = 1;
var b = 0;
//define training function
function training(){
//lg stands for loss gradient or slope how far away it is from the best parameter.
//lga is the loss gradient for parameter a.
//lgb is the loss gradient for parameter b.
var lga = 0;
var lgb = 0;
//msd is mean square error.
var msd = 0;
//data is the array of data that the line is trying to fit.
data.forEach(xx=>{
msd += (xx[1]-(a*xx[0]+b))**2;
lga += -2*xx[0]*(xx[1]-(a*xx[0]+b));
lgb += -2*(xx[1]-(a*xx[0]+b));
});
//new a and b is calcualted, here lga for a is divided by 1000, because lga is far bigger gthan lgb, which
//may result in the line always trying to fit data with a fitting slope not with the y intercept b.
a = a - learningRate*lga/1000;
b = b - learningRate*lgb;
};
Key Points
- If the learing rate is too big, this machine algorithm may never find an answer.
- If parameter a and b have very too big of a gap between their loss gradient, this machine algorithm may find an weird answer.
Comments
Post a Comment