데이터 [:, 1]에 저장된 x 변수의 데이터 [:, 4]에 저장된 y 변수를 회귀하기 위해 다음과 같은 그래디언트 디센트 알고리즘을 적용했습니다. 그러나 그래디언트 디센트는 발산하는 것처럼 보입니다. 내가 잘못하고있는 곳을 찾아내는 데 도움이 될만한 점이 많습니다.R의 회귀에 대한 그라데이션 강하가 실패하는 이유는 무엇입니까?
#define the sum of squared residuals
ssquares <- function(x)
{
t = 0
for(i in 1:200)
{
t <- t + (data[i,4] - x[1] - x[2]*data[i,1])^2
}
t/200
}
# define the derivatives
derivative <- function(x)
{
t1 = 0
for(i in 1:200)
{
t1 <- t1 - 2*(data[i,4] - x[1] - x[2]*data[i,1])
}
t2 = 0
for(i in 1:200)
{
t2 <- t2 - 2*data[i,1]*(data[i,4] - x[1] - x[2]*data[i,1])
}
c(t1/200,t2/200)
}
# definition of the gradient descent method in 2D
gradient_descent <- function(func, derv, start, step=0.05, tol=1e-8) {
pt1 <- start
grdnt <- derv(pt1)
pt2 <- c(pt1[1] - step*grdnt[1], pt1[2] - step*grdnt[2])
while (abs(func(pt1)-func(pt2)) > tol) {
pt1 <- pt2
grdnt <- derv(pt1)
pt2 <- c(pt1[1] - step*grdnt[1], pt1[2] - step*grdnt[2])
print(func(pt2)) # print progress
}
pt2 # return the last point
}
# locate the minimum of the function using the Gradient Descent method
result <- gradient_descent(
ssquares, # the function to optimize
derivative, # the gradient of the function
c(1,1), # start point of theplot_loss(simple_ex) search
0.05, # step size (alpha)
1e-8) # relative tolerance for one step
# display a summary of the results
print(result) # coordinate of fucntion minimum
print(ssquares(result)) # response of function minimum
데이터를 공유 할 수 있습니까? –
이것은 내가 사용하는 데이터 집합입니다. http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv 데이터 <- read.csv ("Advertising.csv") [, - 1] – esperanto
그래디언트 디센트의 발산은 일반적으로 학습 속도가 너무 높다는 것을 나타내므로 학습 속도 (α)를 줄여 수렴합니다. –