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]
}
}