我为梯度下降算法编写了下面的代码。我收到错误,有人可以告诉我为什么以及如何解决它?
gradient <- function(h, start, alpha = 0.01, tolerance = 0.0001, debug = FALSE) {
MAXITER <- 1000
x_old <- start
iter <- 0
cat("gradient descent minimization =\n")
if (debug == TRUE) cat("iter=", iter,", value=", x_old, "\n")
repeat {
iter <- iter + 1
x_new <- x_old - alpha*h(x_old)
if (debug == TRUE) cat("iter=", iter,", value=", x_new, "\n")
if (abs(x_old - x_new) < tolerance) break
if (iter > MAXITER) break
x_old <- x_new
}
cat("total number of interations =", iter, "\n")
cat("last diference =", abs(x_old - x_new), "\n")
cat("final value =", x_new, "\n")
cat("final function value =", h(x_new), "\n")
}
h <- function(x){ x^4 - 8*x^2 + 2*x }
gradient(h, -5, tolerance = 0.0001)
...
gradient descent minimization =
Error in if (abs(x_old - x_new) < tolerance) break :
missing value where TRUE/FALSE needed
答案 0 :(得分:0)
我只是运行你的代码。这里存在数字不稳定性。在if(is.nan(x_new)) break
声明后添加条件x_new <- x_old - alpha*h(x_old)
。