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

R中的多元线性回归-梯度下降,r,machine-learning,linear-regression,R,Machine Learning,Linear Regression,我在学习机器学习。所以我用我在网上找到的数据做了一些简单的练习。现在,我尝试在R中通过梯度下降实现线性回归。当我运行它时,我意识到它不会收敛,我的成本会无限高。虽然我怀疑它在我计算梯度的地方,但我无法找到问题所在。让我们开始展示我的数据 数据集: 我的数据集包含4列:ROLL~UNEM,HGRAD,INC因此,目标是找到ROLL和其他人之间的关系 让我介绍一下我的代码 datavar <- read.csv("dataset.csv") attach(datavar) X <

我在学习机器学习。所以我用我在网上找到的数据做了一些简单的练习。现在,我尝试在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)
    }
    
    这是我得到的输出:

    -7.001406e+118  -5.427330e+119  -1.192040e+123  -1.956518e+122
    
    那么,你能找出我错在哪里吗。我已经尝试了不同的alpha值,但没有产生任何影响。顺便说一句,我很感谢你给我的任何建议或好的做法


    谢谢,我想我终于找到了答案。问题是我没有应用任何功能缩放。因为我认为这是使算法顺利运行的可选程序。现在,它的工作如预期。您可以尝试使用R的scale()函数运行带有缩放数据集的代码。

    好吧,我想我终于找到了答案。问题是我没有应用任何功能缩放。因为我认为这是使算法顺利运行的可选程序。现在,它的工作如预期。您可以尝试使用R的scale()函数运行带有缩放数据集的代码

    -7.001406e+118  -5.427330e+119  -1.192040e+123  -1.956518e+122