線形回帰モデルの勾配降下を計算する関数を作成しようとしました。しかし、私が得た答えは、正規方程式法を使用して得た答えと一致しません。
私のサンプルデータは次のとおりです。
df <- data.frame(c(1,5,6),c(3,5,6),c(4,6,8))
c(4,6,8) は y の値です。
lm_gradient_descent <- function(df,learning_rate, y_col=length(df),scale=TRUE){
n_features <- length(df) #n_features is the number of features in the data set
#using mean normalization to scale features
if(scale==TRUE){
for (i in 1:(n_features)){
df[,i] <- (df[,i]-mean(df[,i]))/sd(df[,i])
}
}
y_data <- df[,y_col]
df[,y_col] <- NULL
par <- rep(1,n_features)
df <- merge(1,df)
data_mat <- data.matrix(df)
#we need a temp_arr to store each iteration of parameter values so that we can do a
#simultaneous update
temp_arr <- rep(0,n_features)
diff <- 1
while(diff>0.0000001){
for (i in 1:(n_features)){
temp_arr[i] <- par[i]-learning_rate*sum((data_mat%*%par-y_data)*df[,i])/length(y_data)
}
diff <- par[1]-temp_arr[1]
print(diff)
par <- temp_arr
}
return(par)
}
この関数を実行すると、
lm_gradient_descent(df,0.0001,,0)
私が得た結果は
c(0.9165891,0.6115482,0.5652970)
正規方程式法を使用すると、
c(2,1,0).
この関数で私が間違っていた場所に誰かが光を当ててくれることを願っています。