R:nls2错过了解决方案

时间:2015-08-07 00:34:16

标签: r nls

我正在尝试拟合双指数函数:

t = seq(0, 30, by = 0.1)
A = 20 ; B = 10 ; alpha = 0.25 ; beta = 0.01
y = A*exp(-alpha*t) + B*exp(-beta*(t))
df = as.data.frame(cbind(t,y))
ggplot(df, aes(t, y)) + geom_line() +  scale_y_continuous(limits=c(0, 50))

enter image description here

这个问题无法通过像 log 之类的简单转换来解决,所以我想使用nls2包:

library(nls2)

fo <- y ~ Ahat*exp(-alphahat*t) + Bhat*exp(-betahat*t)
fit <- nls2(fo,
            start = list(Ahat=5, Bhat=5, alphahat=0.5,betahat=0.5),
            algorithm = "brute-force",
            trace = TRUE,
            lower = c(Ahat=0, Bhat=0, alphahat=0, betahat=0),
            upper = c(Ahat=50, Bhat=50, alphahat=10,betahat=10))
fit

结果如下:

Nonlinear regression model
  model: y ~ Ahat * exp(-alphahat * t) + Bhat * exp(-betahat * t)
   data: NULL
    Ahat     Bhat alphahat  betahat 
     5.0      5.0      0.5      0.5 
 residual sum-of-squares: 37910

Number of iterations to convergence: 4 
Achieved convergence tolerance: NA

我认为我的代码出了问题,因为:

  • 数据:NULL?
  • 为什么只有4次迭代?
  • 很难想到nls2找不到比起点更好的解决方案。
  • 结果远非解决方案

2 个答案:

答案 0 :(得分:3)

从文档中,from time import sleep from circuits import Component, Debugger, handler, Event, Worker, task class my_event(Event): pass def heavy_task(): print "heavy task" sleep(3) class NextHandler(Component): @handler("my_event", priority=10) def my_event(self, event): print "Handler 2" class Handler(Component): _worker = Worker() @handler("my_event", priority=20) def my_event(self, event): self.fire(task(heavy_task), self._worker) print "Handler 1" # how do I delay "event" until "heavy_task" is completed? class App(Component): h1 = Handler() h2 = NextHandler() def started(self, component): print "Running" self.fire(my_event()) if __name__ == '__main__': (App() + Debugger()).run() 参数应该是两行中的start,用于定义要搜索的网格,或者data.frame,其中包含更多行,对应于参数组合以测试是否你正在使用蛮力。另外,data.frame会因你的健康而有问题,因为它是一条完美的曲线,没有噪音。蛮力方法很慢,因此这里是nls的搜索空间减少的示例。然后,在向数据添加一点点噪声之后,蛮力nls2的结果将用作nls2默认算法的起始值(或者您可以使用nls)。

nls2

enter image description here

答案 1 :(得分:1)

您的数据为null,因为您没有将任何数据添加到nls2语句中。

这就是nls2需要设置的方式:

nls2(formula, data = parent.frame(), start, control = nls.control(),
algorithm = c("default", "plinear", "port", "brute-force",
"grid-search", "random-search", "plinear-brute", "plinear-random"),
trace = FALSE, weights, ..., all = FALSE)

查看the official documentation获取完整示例。