如何计算 R 中自定义函数的非线性最小二乘法?

问题描述

我正在尝试使用 this example 之后的自定义函数运行非线性最小二乘法 数据集有 x、预测变量 y 和组 (a/b)。我以前只使用过 MLL 代码。我很难围绕如何将函数调用到 nls 以及如何进行后续 nls 拟合。我附上了我尝试过的代码以及适用的错误

# generate data
set.seed(2)
x <- rep(sample(1:100,9),12)
set.seed(15)
r <- rnorm(x,mean = 0,sd = 200*x^-0.8)
y <- c(200,300) * exp(c(-0.08,-0.05)*x) + c(120,100) + r
df <-  data.frame(x = x,y = y,group = rep(letters[1:2],length.out = length(x)))

ga <- function(aa,K,Ka,q,c){
  p <- x / K
  lnqp <- if (q == 0) log(p) else (p^q - 1) / q
  y <- (aa * (p * K / Ka - 1) - 1) * lnqp + c
}

m <- nls(y ~ ga(aa,c))

Error in q == 0 : 
  comparison (1) is possible only for atomic and list types
In addition: Warning message:
In nls(y ~ ga(aa,c)) :
  No starting values specified for some parameters.
Initializing ‘aa’,‘K’,‘Ka’ to '1.'.
Consider specifying 'start' or using a selfStart model

summary(m) 
plot(m) 

#ERROR: Error in q == 0 : 
comparison (1) is possible only for atomic and list types


# fit generalised nonlinear least squares
require(nlme)
mgnls <- gnls(y ~ ga(aa,c),start = list(aa = c(356.6851,356.6851),K = c(-exp(-2.9356),-exp(-2.9356)),Ka = c(-exp(-2.9356),q = c(-exp(-2.9356),c = c(108.9860,108.9860)),params = list(aa ~ group,K ~ group,Ka ~ group,q ~ group,c ~ group),weights = varExp(),data = df)
plot(mgnls) # more homogenous

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)