[R] linear regression Normal Equation
linear regression을 학습하는데, Normal Equation 방정식으로 풀기.
+Computing parameters analytically
#
# deep learning test
#
# linear regression ; test.. y=2x+1 learning
#
# training , X1=1 (bias)
X=matrix( c(1,1,1 , 1,2,3), nrow=3 )
# training result Y
Y=matrix( c(3,5,7) )
# searching parameter, w1=bias
W=c(2,2)
# H(X,W)=w1+ w2*x2
H = function (X, W) {
H = X %*% W
return (H)
}
Cost =function (X, W, Y) {
m = nrow(X)
return (sum((H(X,W)-Y)^2) / m)
}
NormalEquation = function (X, W, Y) {
# no need alpha
# no iteration
# S = inv( t(X) X ) t(X) Y
W = solve( t(X) %*% X ) %*% t(X) %*% Y
return (W)
}
print( Cost(X, W, Y) )
#learning
W = NormalEquation(X, W, Y)
print(paste(" Cost=", Cost(X,W,Y), " W1(b)=", W[1,1], " W2=", W[2,1]) )
# predict
qx = c(7,8,9)
xmat = cbind( rep(1, length(qx)), qx)
qy = H( xmat, W )
print (qx)
print (qy)
[1] 1
[1] " Cost= 3.15544362088405e-30 W1(b)= 1 W2= 2"
[1] 7 8 9
[,1]
[1,] 15
[2,] 17
[3,] 19