【发布时间】:2017-01-02 08:55:45
【问题描述】:
我正在学习机器学习。所以我用我在网上找到的数据做了一些简单的练习。现在我尝试在 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 machine-learning linear-regression