【问题标题】:Multivariate Linear Regression - Gradient Descent in R多元线性回归 - R 中的梯度下降
【发布时间】: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


    【解决方案1】:

    嗯,我想我终于找到了答案。问题是我没有应用任何特征缩放。虽然我认为这是平稳运行算法的可选程序。现在它按预期工作。您可以尝试使用 R 的 scale() 函数运行带有缩放数据集的代码。

    【讨论】:

      猜你喜欢
      • 2017-06-20
      • 2019-10-09
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 2016-10-22
      相关资源
      最近更新 更多