簡體   English   中英

R 中 nls() function 的正確語法

[英]Right syntax for nls() function in R

我對 R 相當陌生,我正在嘗試使用 nls function 擬合曲線。 我將首先使用 dgamma function 生成曲線 y,然后我想使用 nls 對其進行擬合。 這是我的玩具示例。

´´´
x <- 1:250
y <- dgamma(x,2,0.02)
df <- data.frame(x=x,y=y)

nls(y~ dgamma(x,a,b),data=df,start =  list(a =2,b =0.4))
´´´

我得到的錯誤是

numericDeriv(form[[3L]], names(ind), env) 中的錯誤:在評估 model 時產生缺失值或無窮大另外:警告消息:在 dgamma(x, a, b) 中:產生 NaN

我在這里做錯了什么?

謝謝

1) nls這不是語法錯誤。 算法不收斂。 問題是:

  • dgamma 產生大和/或小的數字,導致數值不穩定

  • nls往往存在零殘差數據的問題,即精確擬合。 if you are using R 4.1, currently the development version of R, then adding the nls argument control = nls.control(scaleOffset = 1) may help to avoid such problems ( see https://stat.ethz.ch/R-manual /R-devel/library/stats/html/nls.control.html )。 下面我們設法在沒有scaleOffset的情況下獲得收斂,因此它將適用於當前版本的 R。

使用樣條擬合來創建更多點,例如 1000,然后擬合 log(y) 而不是 y。 使用該結果來擬合原始方程,繼續使用附加點。

x <- 1:250
y <- dgamma(x, 2, 0.02)

xx <- seq(1, 250, length = 1000)
spl <- spline(x, y, xout = xx)

fo.log <- log(y) ~ dgamma(x, a, b, log = TRUE)
fm.log <- nls(fo.log, data = spl, start = list(a = 2, b = 0.4))

fo <- y ~ dgamma(x, a, b)
fm <- nls(fo, spl, start = coef(fm.log))
fm

給予:

Nonlinear regression model
  model: y ~ dgamma(x, a, b)
   data: spl
   a    b 
2.00 0.02 
 residual sum-of-squares: 4.399e-19

Number of iterations to convergence: 1 
Achieved convergence tolerance: 7.806e-08

2) optim optim通常適用於非線性最小二乘問題。 有了它,我們可以直接獲得合身,而無需上述解決方法。 產生的警告在達到收斂時可以忽略(輸出中的convergence = 0 )。

rss <- function(p, x, y) sum((y - dgamma(x, p[["a"]], p[["b"]]))^2)
optim(c(a = 2, b = 0.4), rss, x = x, y = y)

給予:

$par
        a         b 
1.9974423 0.0199842 

$value
[1] 5.209388e-09

$counts
function gradient 
      61       NA 

$convergence
[1] 0

$message
NULL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM