2017-02-20 37 views
0

我試圖用nls()函數來擬合數據,其中數據的性質使得我可以限制一個係數和兩個係數的總和。讓我來介紹一個簡短的例子,看看問題出在哪裏。我希望參數b1介於0和1之間,我希望參數b1和b2之和也介於0和1之間。nls係數的約束

set.seed(123) 

# example where everything is OK 
x <- 1:200 
g <- rbinom(200, 1, 0.5) 
y <- 3 + (0.7 + 0.2 * g) * x 
yeps <- y + rnorm(length(y), sd = 0.1) 

# both parameter b1 and sum of parameters b1 and b2 are between 0 and 1 
nls(yeps ~ a + (b1 + b2 * g) * x, start = list(a = 0.12345, b1 = 0.54321, b2 = 0.4213)) 

# using more extreme values 
x <- 1:200 
g <- rbinom(200, 1, 0.5) 
y <- 3 + (0.9 - 0.99 * g) * x 
yeps <- y + rnorm(length(y), sd = 15) 

# b1 is OK, but b1 + b2 < 0 
nls(yeps ~ a + (b1 + b2 * g) * x, 
    start = list(a = 0.12345, b1 = 0.54321, b2 = 0.4213)) 

# trying constraints, not good, sum is still out of range 
nls(yeps ~ a + (b1 + b2 * g) * x, 
    start = list(a = 0.12345, b1 = 0.54321, b2 = 0.4213), 
    lower = list(a = -Inf, b1 = 0, b2 = -1), 
    upper = list(a = Inf, b1 = 1, b2 = 1), 
    algorithm = "port") 

我正在尋找的是這樣的事情(不工作):

nls(yeps ~ a + (b1 + b2 * g) * x, 
    start = list(a = 0.12345, b1 = 0.54321, b2 = 0.4213), 
    lower = list(a = -Inf, b1 = 0, b2 = -b1), 
    upper = list(a = Inf, b1 = 1, b2 = 1 - b1), 
    algorithm = "port") 

是否有可能設置與其它參數約束nls()功能?感謝您的任何建議!

+0

看看這個[問題](http://stackoverflow.com/q/11589139/707145)。 – MYaseen208

+0

感謝您的提示。但是,我不確定'ifelse'是否是'nls'函數的好方法,請參閱http://stats.stackexchange.com/questions/14561/specifying-parameter-constraints-in-nls – Adela

+0

無論如何,這種方法與爲每個「g」組擬合兩種模型有什麼不同? – Adela

回答

2

設B2 = B1 + B2所以B2 = B2-B1和B2代替B2-B1我們在A,B1和B2的術語,其中後兩者是0和1之間,從而得到了一個問題:

fm <- nls(yeps ~ a + (b1 + (B2-b1) * g) * x, lower = c(-Inf, 0, 0), upper = c(Inf, 1, 1), 
    start = list(a = 0.1, b1 = 0.5, B2 = 0.1), alg = "port") 

給出以下(因此B2 = B2 - B1 = 0 - 0.9788 = -0.9788)

> fm 
Nonlinear regression model 
    model: yeps ~ a + (b1 + (B2 - b1) * g) * x 
    data: parent.frame() 
     a  b1  B2 
-5.3699 0.9788 0.0000 
residual sum-of-squares: 42143 

Algorithm "port", convergence message: both X-convergence and relative convergence (5) 

和繪圖:

plot(yeps ~ x) 
points(fitted(fm) ~ x, pch = 20, col = "red") 

screenshot

+0

這是更優雅的解決方案。感謝這個提示! – Adela