多元线性回归 - R 中的梯度下降
Multivariate Linear Regression - Gradient Descent in R
我正在学习机器学习。所以我用我在网上找到的数据做了一些简单的练习。现在我尝试在 R 中通过梯度下降来实现线性回归。当我 运行 它时,我意识到它不收敛并且我的成本无限上升。虽然我怀疑它在我计算梯度的部分的某个地方,但我找不到问题所在。因此,让我们开始展示我的数据。
我的数据集包含 4 列:ROLL ~ UNEM, HGRAD, INC
所以,目标是找到 ROLL
和其他人之间的关系。
让我展示我的代码
datavar <- read.csv("dataset.csv")
attach(datavar)
X <- cbind(rep(1, 29), UNEM,HGRAD,INC)
y <- ROLL
# function where I calculate my prediction
h <- function(X, theta){
return(t(theta) %*% X)
}
# function where I calculate the cost with current values
cost <- function(X, y, theta){
result <- sum((X %*% theta - y)^2 ) / (2*length(y))
return(result)
}
# here I calculate the gradient,
#mathematically speaking I calculate derivetive of cost function at given points
gradient <- function(X, y, theta){
m <- nrow(X)
sum <- c(0,0,0,0)
for (i in 1 : m) {
sum <- sum + (h(X[i,], theta) - y[i]) * X[i,]
}
return(sum)
}
# The main algorithm
gradientDescent <- function(X, y, maxit){
alpha <- 0.005
m <- nrow(X)
theta <- c(0,0,0,0)
cost_history <- rep(0,maxit)
for (i in 1 : maxit) {
theta <- theta - alpha*(1/m)*gradient(X, y, theta)
cost_history[i] <- cost(X, y, theta)
}
plot(1:maxit, cost_history, type = 'l')
return(theta)
}
我运行这样的代码
gradientDescent(X, y, 20)
这是我得到的输出:
-7.001406e+118 -5.427330e+119 -1.192040e+123 -1.956518e+122
所以,你能找出我错在哪里吗?我已经尝试过不同的 alpha 值,但没有什么不同。顺便说一下,我很感谢你的任何提示或好的做法,
谢谢
好吧,我想我终于找到了答案。问题是我没有应用任何特征缩放。因为我认为它是 运行 算法顺利运行的可选程序。现在它按预期工作。您可以尝试 运行 使用 R 的 scale() 函数对缩放数据集进行编码。
我正在学习机器学习。所以我用我在网上找到的数据做了一些简单的练习。现在我尝试在 R 中通过梯度下降来实现线性回归。当我 运行 它时,我意识到它不收敛并且我的成本无限上升。虽然我怀疑它在我计算梯度的部分的某个地方,但我找不到问题所在。因此,让我们开始展示我的数据。
我的数据集包含 4 列:ROLL ~ UNEM, HGRAD, INC
所以,目标是找到 ROLL
和其他人之间的关系。
让我展示我的代码
datavar <- read.csv("dataset.csv") attach(datavar) X <- cbind(rep(1, 29), UNEM,HGRAD,INC) y <- ROLL # function where I calculate my prediction h <- function(X, theta){ return(t(theta) %*% X) } # function where I calculate the cost with current values cost <- function(X, y, theta){ result <- sum((X %*% theta - y)^2 ) / (2*length(y)) return(result) } # here I calculate the gradient, #mathematically speaking I calculate derivetive of cost function at given points gradient <- function(X, y, theta){ m <- nrow(X) sum <- c(0,0,0,0) for (i in 1 : m) { sum <- sum + (h(X[i,], theta) - y[i]) * X[i,] } return(sum) } # The main algorithm gradientDescent <- function(X, y, maxit){ alpha <- 0.005 m <- nrow(X) theta <- c(0,0,0,0) cost_history <- rep(0,maxit) for (i in 1 : maxit) { theta <- theta - alpha*(1/m)*gradient(X, y, theta) cost_history[i] <- cost(X, y, theta) } plot(1:maxit, cost_history, type = 'l') return(theta) }
我运行这样的代码
gradientDescent(X, y, 20)
这是我得到的输出:
-7.001406e+118 -5.427330e+119 -1.192040e+123 -1.956518e+122
所以,你能找出我错在哪里吗?我已经尝试过不同的 alpha 值,但没有什么不同。顺便说一下,我很感谢你的任何提示或好的做法,
谢谢
好吧,我想我终于找到了答案。问题是我没有应用任何特征缩放。因为我认为它是 运行 算法顺利运行的可选程序。现在它按预期工作。您可以尝试 运行 使用 R 的 scale() 函数对缩放数据集进行编码。