You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用optimize函数求极大似然图最大值时遇参数错误问题咨询

Fix: Error in f(arg, ...) : unused argument (arg) with optimize() in R

Hey there, that error is super straightforward to fix—let's break it down:

The core issue is that the optimize() function automatically passes a single argument (the current value it's evaluating in your interval) to your target function, but your fml() function doesn't accept any arguments at all.

Looking at your fml definition:

fml<-function(){ 
  q1<- Nominal(z, a, c, x[1]) 
  q2<- Nominal(z, a, c, x[2]) 
  p3<- Nominal(z, a, c, x[3]) 
  q4<- Nominal(z, a, c, x[4]) 
  p1<- 1 - q1 
  p2<- 1 - q2 
  p4<- 1 - q4 
  p <- p1*p2*p3*p4 
  q <- 1-p
  # Looks like you're missing a return statement here too!
}

Step-by-step fixes:

  • Add a parameter to fml: Since optimize() is for single-variable optimization, it will pass the value it's testing to the first argument of your function. Let's name it something meaningful, like theta (the parameter you're trying to maximize the likelihood for).
  • Update your function to use this parameter: Replace the value you want to optimize with theta (I'm guessing one of the inputs to Nominal() is your target parameter—adjust this to match your actual logic).
  • Return the likelihood value: optimize() needs a numeric value to maximize/minimize, so make sure your function returns q (or p, depending on which is your likelihood metric).
  • Check variable scope: Ensure z, a, c, and x are available in the environment where fml runs (either global environment, or pass them as additional arguments if needed).

Here's the revised code example:

# Define the function with a parameter for the value to optimize
fml <- function(theta){ 
  # Replace x[1] with theta (adjust this to match your actual optimization target)
  q1 <- Nominal(z, a, c, theta)  
  q2 <- Nominal(z, a, c, x[2]) 
  p3 <- Nominal(z, a, c, x[3]) 
  q4 <- Nominal(z, a, c, x[4]) 
  
  p1 <- 1 - q1 
  p2 <- 1 - q2 
  p4 <- 1 - q4 
  
  p <- p1 * p2 * p3 * p4 
  q <- 1 - p
  
  return(q)  # Return the value we want to maximize
}

# Now call optimize() without errors
optimize(f = fml, interval = c(-10,10), maximum = TRUE)

Quick extra note:

If you're trying to optimize multiple parameters (not just one), optimize() won't work—you'll need to use optim() instead, which handles multi-variable optimization. Also, double-check that your Nominal() function is defined correctly and that all dependencies are accessible to fml.

内容的提问来源于stack exchange,提问作者Admovin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:01:14