简体   繁体   English

向R中的非线性模型添加约束

[英]Add a constraint to a nonlinear model in R

I'm having trouble adding a constraint to my nonlinear model. 我在向非线性模型添加约束时遇到了麻烦。 Suppose I have the following data that is roughly an integrated Gaussian: 假设我有以下数据,它们大致是一个集成的高斯:

x = 1:100
y = pnorm(x, mean = 50, sd = 15) + rnorm(length(x), mean = 0, sd = 0.03)
model <- nls(y ~ pnorm(x, mean = a, sd = b), start = list(a = 50, b = 15))

I can fit the data with nls , but I would like to add the constraint that my fit must fit the data exactly (ie have no residual) at y = 0.25 (or whatever point is closest to 0.25). 我可以使用nls拟合数据,但我想添加一个约束,即我的拟合必须在y = 0.25(或最接近0.25的任何点)时精确拟合数据(即没有残差)。 I assume that I need to use glmc for this, but I can't figure out how to use it. 我认为我需要为此使用glmc ,但是我不知道如何使用它。

I know it's not necessarily kosher to make the fit adhere to the data like that, but I'm trying to replicate another person's work and this is what they did. 我知道不一定要使拟合符合这样的数据,但是我正在尝试复制他人的工作,这就是他们所做的。

You could impose the restriction somewhat manually. 您可以手动施加限制。 That is, for any parameter b we can solve for a unique a (since the cdf of the normal distribution is strictly increasing) that the restriction would hold: 也就是说,对于任何参数b我们都可以求解唯一性a (因为正态分布的cdf严格增加),该限制将成立:

getA <- function(b, x, y)
  optim(x, function(a) (pnorm(x, mean = a, sd = b) - y)^2, method = "BFGS")$par

Then, after finding (tx,ty) , the observation of interest, with 然后,在找到(tx,ty)之后,用

idx <- which.min(abs(y - 0.25))
tx <- x[idx]
ty <- y[idx]

we can fit the model with a single parameter: 我们可以用一个参数拟合模型:

model <- nls(y ~ pnorm(x, mean = getA(b, tx, ty), sd = b), start = list(b = 15))

and get that the restriction is satisfied 得到限制满足

 resid(model)[idx]
# [1] -2.440452e-07

and the coefficient a is 系数a

getA(coef(model), tx, ty)
# [1] 51.00536

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM