gpt4 book ai didi

R_using nlsLM() 有约束

转载 作者:行者123 更新时间:2023-12-04 10:44:28 25 4
gpt4 key购买 nike

我正在使用 nlsLM {minpack.lm}查找参数值ab功能 myfun最适合数据集,mydata .

mydata=data.frame(x=c(0,5,9,13,17,20),y = c(0,11,20,29,38,45))

myfun=function(a,b,r,t){
prd=a*b*(1-exp(-b*r*t))
return(prd)
}

并使用 nlsLM
myfit=nlsLM(y~myfun(a,b,r=2,t=x),data=mydata,start=list(a=2000,b=0.05),
lower = c(1000,0), upper = c(3000,1))

有用。但现在我想介绍一个约束,它是 a*b<1000 .我查看了 nlsLM 中可用的选项通过 nls.lm.control 设置约束.但这并没有多大帮助。有人可以在这里帮助我或提出不同的方法吗?

最佳答案

据我所知,在 minpack.lm 包的 nlsLM 中,参数上下限是唯一可用的约束。
解决您的问题的一种可能方法是使用包 nloptr ,免费开源库的 R 接口(interface) NLopt 用于非线性优化。
在下面的代码中,我使用 cobyla , 一种具有非线性不等式和等式约束的无导数优化算法:

mydata <- data.frame(x=c(0,5,9,13,17,20), y=c(0,11,20,29,38,45))

myfun=function(a,b,r,t){
prd=a*b*(1-exp(-b*r*t))
return(prd)
}

library(nloptr)

sse <- function(ab,r,x,y){
sum((y - myfun(ab[1],ab[2],r,x))^2)
}

nonlincons <- function(ab,r,x,y) {
h <- numeric(1)
h[1] <- 1000 - ab[1]*ab[2]
return(h)
}

x0 <- c(2000,0.05)
optpar <- cobyla(x0=x0, fn=sse, lower = c(1000,0), upper = c(3000,1),
hin=nonlincons, r=2, x=mydata$x, y=mydata$y,
control = list(xtol_rel = 1e-12, maxeval = 20000))
(optpar <- optpar$par)

sum((mydata$y-myfun(optpar[1],optpar[2],r=2,mydata$x))^2)

最佳参数的值为:
[1] 3.000000e+03 2.288303e-02

误差平方和为:
[1] 38.02078

希望它可以帮助你。

关于R_using nlsLM() 有约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44615030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com