簡體   English   中英

R中的多元線性回歸-梯度下降

[英]Multivariate Linear Regression - Gradient Descent in R

我正在學習機器學習。 因此,我對在網上找到的數據做了一些簡單的練習。 現在,我嘗試通過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的scale()函數對縮放后的數據集運行代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM