【发布时间】:2019-10-09 16:12:17
【问题描述】:
我有一个目标函数 f(x, d),其中 x 是两个变量 (x1, x2) 的向量,d 是给定的 Nx2 点矩阵。 f(x) 是一个距离函数,计算从 x 到 d 中所有点的某个复合距离。
我正在尝试创建一个梯度下降函数来计算函数的最小值。首先,我创建了一个梯度函数,它依赖于给定的外部参数 d(见下文)。
# Customers location from an external file (100 customers)
locations = read.csv(file = 'locations.csv')
# Gradient of my objective function is:
obj_fun.grad <- function(x,d) {
dx <- 2*(x[1] - d$x)/((x[1] - d$x)^2 + 1)
dy <- 2*(x[2] - d$y)/((x[2] - d$y)^2 + 1)
s <- c(sum(dx),sum(dy))
return (s)
}
然后我创建了如下的梯度下降函数。我想让这个函数尽可能通用,以便可重复用于其他目标函数。
grad.descent = function(grad.function, x0, max.iter=200, step.size=0.05, stopping.deriv=0.01,...)
{
# Calculating the length of the initial vector
n = length(x0)
# Create a matrix where the coordinates of different steps will be stored
xmat = matrix(0, nrow=n, ncol=max.iter)
# Initial guess is the starting point
xmat[,1] = x0
for (k in 2:max.iter) {
# Calculate the gradient, that depends on locations of customers
grad.cur = grad.function(xmat[,k-1], d=d)
# Check whether gradient is below the given threshold
if (sqrt(t(grad.cur)%*%grad.cur) < stopping.deriv) {
k = k-1;
break
}
# Move in the opposite direction of the grad
xmat[,k] = xmat[,k-1] - step.size*grad.cur
}
# Remove unused positions
xmat = xmat[,1:k]
# Return: 1) optimum position, 2) list of all positions, 3) number of iterations
return(list(x=xmat[,k], xmat=xmat[,1:k], k=k))
}
现在我想调用 grad.descent 函数,如果将位置文件作为附加参数传递给梯度函数:
gd1 <- grad.descent(obj_fun, x0 = c(200,200), max.iter = 200, step.size=0.5, locations)
但是,我收到以下错误:
fgrad(xmat[, k - 1], d = d) 中的错误:找不到对象“d”
【问题讨论】:
-
请发布您的完整示例。可能您也需要将
d传递给grad.descent。 -
我认为你只需要这样做,所以
grad.descent需要一个额外的参数,例如grad.descent = function(f, x0, d, max.iter=200, <etc.>)。除非我遗漏了一些让事情变得更复杂的东西? -
大家好,感谢您的帮助。我还考虑将 d 作为参数添加到 grad.descent 函数,但我想知道是否可以使它更通用:)
-
@Cettt d 是包含在 locations.csv 中的内容。非常感谢您的耐心和支持
标签: r function parameters