Published
Edited
Dec 2, 2021
1 star
Insert cell
Insert cell
class Regression{
constructor(X1,X2,Y,rate,epochs){
this.X1 = X1
this.X2 = X2
this.Y = Y
this.rate = rate
this.epochs = epochs
}

mse(w2,w1,b){
const Yhat =this.X1.map((x,i) => w2*this.X2[i] + w1*this.X1[i] + b)
const differences = this.X1.map((x,i)=>this.Y[i]-Yhat[i])
const squares = differences.map(d => d*d)
const mse = d3.mean(squares)
return mse
}

msePartialw2(w2,w1,b){
const Yhat =this.X1.map((x,i) => w2*this.X2[i] + w1*this.X1[i] + b)
const summand = this.X1.map((x,i) => (this.Y[i]-Yhat[i])*this.X2[i])
return -2*d3.sum(summand)/this.X1.length
}

msePartialw1(w2,w1,b){
const Yhat =this.X1.map((x,i) => w2*this.X2[i] + w1*this.X1[i] + b)
const summand = this.X1.map((x,i) => (this.Y[i]-Yhat[i])*this.X1[i])
return -2*d3.sum(summand)/this.X1.length
}

msePartialb(w2,w1,b){
const Yhat =this.X1.map((x,i) => w2*this.X2[i] + w1*this.X1[i] + b)
const summand = this.X1.map((x,i) => (this.Y[i]-Yhat[i]))
return -2*d3.sum(summand)/this.X1.length
}

fit(){
let w1 = 0
let w2 = 0
let b = 0
for(let i = 0; i <= this.epochs; i = i + 1){
w1 = w1 - this.rate*this.msePartialw1(w2,w1,b)
w2 = w2 - this.rate*this.msePartialw2(w2,w1,b)
b = b - this.rate*this.msePartialb(w2,w1,b)
}
return [w2,w1,b]
}

}
Insert cell
X1 = [3,6,4,1]
Insert cell
X2 = [7,6,9,5]
Insert cell
Y = [3,7,5,8]
Insert cell
regression = new Regression(X1,X2,Y,.0001,1000)
Insert cell
p = regression.fit()
Insert cell
regression.mse(p[0],p[1],p[2])
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more