多元线性回归 - R中的梯度下降

时间:2016-08-25 19:41:57

标签: r machine-learning linear-regression

我正在学习机器学习。所以我用在网上找到的数据做了一些简单的练习。现在我尝试通过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值,没有什么区别。顺便说一句,我感谢你的任何提示或良好做法,

谢谢

1 个答案:

答案 0 :(得分:2)

嗯,我想我终于找到了答案。问题是我没有应用任何功能扩展。 Couse I虽然它是可选的,可以顺利运行算法。现在它按预期工作。您可以尝试使用R的scale()函数运行带有缩放数据集的代码。

相关问题