优化非线性模型拟合

时间:2015-01-08 16:31:20

标签: r

我想找到最适合我的数据曲线的参数,我觉得我已经设置得很好,但是当我运行我的优化功能时,我只是回到起始参数。

rick<-function(x, a, b){
        x*a*exp(-x/b)
   }

x<-df$WaterInput
a<-.1
b<-460

pred<- rick(t, a, b)
predD<-as.data.frame(pred)
predD$WI<-df$WaterInput

plot(WUEs~WaterInput, data=df)
points(predD$WI, predD$pred, type="p", col="red") 


### Optimization attempt###

obfun<- function(coef, x){

    sim<- rick(x=x, a=coef[1], b=coef[2])
    simD<-as.data.frame(pred)
    simD$day<-df$WaterInput

    obs<- df$WUEs

    rss <- sum((obs - simD$pred)^2)
    rss
}

op.wi<- optim(c(.1, 460), obfun, x=df$WaterInput)

可在此处找到数据框:https://www.dropbox.com/s/kns2h2zcqtagwns/WUE%20for%20SO.txt?dl=0

2 个答案:

答案 0 :(得分:2)

这只是因为你没有在优化中使用系数。现在,您正在调用rick(),然后将返回的值分配给sim,但之后您不会在目标函数rss中使用它。您的示例中还有t,但您没有提供。

我想你想要这样的东西:

rick <- function(x, a, b){
        x*a*exp(-x/b)
}

x <- df$WaterInput
a <- .1
b <- 460

pred <- rick(x, a, b)
predD <- as.data.frame(pred)
predD$WI <- df$WaterInput

plot(WUEs~WaterInput, data=df)
points(predD$WI, predD$pred, type="p", col="red") 

obfun <- function(coef, x){
    sim <- rick(x=x, a=coef[1], b=coef[2])
    obs <- df$WUEs
    rss <- sum((obs - sim)^2)
    rss
}

op.wi <- optim(c(.2, 460), obfun, x=df$WaterInput)
points(x, rick(x, op.wi$par[1], op.wi$par[2]),col=3)

enter image description here

答案 1 :(得分:1)

也许以下是您的替代方案(但是您需要良好的起始值,而不是a和b)

dat <- read.table("WUE for SO.txt", header=TRUE)

mod <- nls(WUEs ~ WaterInput*a*exp(-WaterInput/b), 
           data=dat,
           start=list(a=0.1,b=500))

plot(WUEs ~ WaterInput, dat)

tt <- 100:1300
lines(tt, predict(mod, list(WaterInput = tt)))

summary(mod)

Parameters:
Estimate Std. Error t value Pr(>|t|)    
a 8.384e-02  7.065e-03   11.87   <2e-16 ***
b 4.977e+02  3.414e+01   14.58   <2e-16 ***

enter image description here