我正在学习机器学习。因此,我使用在线找到的数据进行了一些简单的练习。现在,我尝试在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 predictionh <- function(X, theta){ return(t(theta) %*% X)}# function where I calculate the cost with current valuescost <- 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 pointsgradient <- 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()函数对数据集进行缩放后运行代码。