2015-05-01 68 views
1

我試圖使用minpack.lm中的nls.lm函數來適應非線性模型對心理物理實驗的某些數據。R中的nls.lm模型擬合「錯誤:未使用的參數」

我已經搜索過了,找不到很多關於軟件包的信息,所以基本上已經複製了nls.lm幫助頁面上給出的示例格式。不幸的是我的腳本仍然失敗運行和R拋出了這個錯誤:

Error in fn(par, ...) : 
unused argument (observed = c(0.1429, 0.2857, 0.375, 0.3846, 0.4667, 0.6154)) 

看來,腳本認爲我要擬合模型的數據是無關緊要的,這肯定是不對的。

我期待它適合模型,併爲備用參數(w)產生0.5403的值。

任何幫助,非常感謝。 我正在從Matlab轉移到R,所以如果我的代碼看起來sl ap的道歉。

這是腳本。

install.packages("pracma") 
    require(pracma) 
    install.packages("minpack.lm") 
    require(minpack.lm) 

    # Residual function, uses parameter w (e.g. .23) to predict accuracy error at a given ratio [e.g. 2:1] 
    residFun=function(w,n) .5 * erfc(abs(n[,1]-n[,2])/ ((sqrt(2)*w) * sqrt((n[,1]^2) + (n[,2]^2)))) 

    # example for residFun 
    # calculates an error rate of 2.59% 
    a=matrix(c(2,1),1,byrow=TRUE) 
    residFun(.23,a) 

    # Initial guess for parameter to be fitted (w) 
    parStart=list(w=0.2) 

    # Recorded accuracies in matrix, 1- gives errors to input into residFun 
    # i.e. the y-values I want to fit the model 
    Acc=1-(matrix(c(0.8571,0.7143,0.6250,0.6154,0.5333,0.3846),ncol=6)) 

    # Ratios (converted to proportions) used in testing 
    # i.e. the points along the x-axis to fit the above data to 
    Ratios=matrix(c(0.3,0.7,0.4,0.6,0.42,0.58,0.45,0.55,0.47,0.53,0.49,0.51),nrow=6,byrow=TRUE) 

    # non-linear model fitting, attempting to calculate the value of w using the Levenberg-Marquardt nonlinear least-squares algorithm 
    output=nls.lm(par=parStart,fn=residFun,observed=Acc,n=Ratios) 

    # Error message shown after running 
    # Error in fn(par, ...) : 
    # unused argument (observed = c(0.1429, 0.2857, 0.375, 0.3846, 0.4667, 0.6154)) 

回答

2

該錯誤意味着你傳遞了一個函數,它沒有期望的參數。 ?nls.lm沒有參數observed,所以它被傳遞給傳遞給fn的函數,在你的情況下,residFun。但是,residFun也不期望這個論點,因此錯誤。你需要重新定義這個函數是這樣的:

# Residual function, uses parameter w (e.g. .23) to predict accuracy error at a given ratio [e.g. 2:1] 
residFun=function(par,observed, n) { 
    w <- par$w 
    r <- observed - (.5 * erfc(abs(n[,1]-n[,2])/ ((sqrt(2)*w) * sqrt((n[,1]^2) + (n[,2]^2))))) 
    return(r) 
} 

它提供了以下結果:

> output = nls.lm(par=parStart,fn=residFun,observed=Acc,n=Ratios) 
> output 
Nonlinear regression via the Levenberg-Marquardt algorithm 
parameter estimates: 0.540285874836135 
residual sum-of-squares: 0.02166 
reason terminated: Relative error in the sum of squares is at most `ftol'. 

爲什麼會發生:

看來你被這個例子中,他documentation啓發:

## residual function 
residFun <- function(p, observed, xx) observed - getPred(p,xx) 
## starting values for parameters 
parStart <- list(a=3,b=-.001, c=1) 
## perform fit 
nls.out <- nls.lm(par=parStart, fn = residFun, observed = simDNoisy, 
xx = x, control = nls.lm.control(nprint=1)) 

請注意,observed這裏是一個參數residFun

+0

啊!謝謝!我知道這將是明顯的事情。 所以這應該工作(至少直到下一個錯誤)? ((n [,1] -n [,2])/((sqrt(2)* w)* sqrt((n [ ,1]^2)+(n [,2]^2))))' –

+1

不,它不起作用,因爲'observed'不是你的函數的參數,而是它的輸出。我更新了一個函數 – scoa

+0

我的答案謝謝,非常感謝。 –

相關問題