【问题标题】:How to pass parameters to a function that is the argument of another function如何将参数传递给作为另一个函数的参数的函数
【发布时间】: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 &lt;- 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, &lt;etc.&gt;)。除非我遗漏了一些让事情变得更复杂的东西?
  • 大家好,感谢您的帮助。我还考虑将 d 作为参数添加到 grad.descent 函数,但我想知道是否可以使它更通用:)
  • @Cettt d 是包含在 locations.csv 中的内容。非常感谢您的耐心和支持

标签: r function parameters


【解决方案1】:

R 告诉您找不到对象 d,因为您从未告诉它 d 是什么。

修复它的最简单方法是将grad.descent函数中for循环内的第一行替换为以下行:

grad.cur = grad.function(xmat[,k-1], d = locations)

这样,函数grad.function 知道它应该将数据帧locations 作为其第二个输入d

请注意,这是因为 R 使用了词法作用域。您可以找到更多信息here

【讨论】:

  • 谢谢 Cettt。我想知道 grad.descent 函数是否有办法接受一些在其中使用的通用可选参数。但我有你的解决方案。
猜你喜欢
  • 2017-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 2023-01-12
  • 2013-11-19
相关资源
最近更新 更多