Ger*_*lix 2 r curve-fitting nls
我正在尝试将 Boltzmann sigmoid 拟合1/(1+exp((x-p1)/p2))到这个小型实验数据集:
xdata <- c(-60,-50,-40,-30,-20,-10,-0,10)
ydata <- c(0.04, 0.09, 0.38, 0.63, 0.79, 1, 0.83, 0.56)
Run Code Online (Sandbox Code Playgroud)
我知道这很简单。例如,使用nls:
fit <-nls(ydata ~ 1/(1+exp((xdata-p1)/p2)),start=list(p1=mean(xdata),p2=-5))
Run Code Online (Sandbox Code Playgroud)
我得到以下结果:
Formula: ydata ~ 1/(1 + exp((xdata - p1)/p2))
Parameters:
Estimate Std. Error t value Pr(>|t|)
p1 -33.671 4.755 -7.081 0.000398 ***
p2 -10.336 4.312 -2.397 0.053490 .
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.1904 on 6 degrees of freedom
Number of iterations to convergence: 13
Achieved convergence tolerance: 7.079e-06
Run Code Online (Sandbox Code Playgroud)
但是,我需要(由于理论原因)拟合曲线精确地通过点(-70, 0)。尽管上面显示的拟合表达式的值在 处接近零x = -70,但它并不完全为零,这不是我想要的。
所以,问题是:有没有办法告诉nls(或其他函数)拟合相同的表达式但强制它通过指定的点?
更新:
正如评论中提到的那样,使用我提供的函数(Boltzmann sigmoid)强制拟合通过点 (-70,0) 在数学上是不可能的。另一方面,@Cleb 和@BenBolker 已经解释了如何强制拟合通过任何其他点,例如 (-50, 0.09)。
正如我们在您的问题下方的评论中所讨论的那样,使用您提供的函数(没有偏移)无法强制拟合通过 0。
但是,您可以通过设置weights单个数据点来强制曲线通过其他数据点。因此,例如,如果您给数据点 A 的权重等于 1,给数据点 B 的权重等于 1000,则数据点 B 更重要(就将要最小化的残差总和的贡献而言)拟合比 A 和拟合因此将被迫通过 B。
这是整个代码,我在下面更详细地解释它:
# your data
xdata <- c(-60, -50, -40, -30, -20, -10, -0, 10)
ydata <- c(0.04, 0.09, 0.38, 0.63, 0.79, 1, 0.83, 0.56)
plot(xdata, ydata, ylim=c(0, 1.1))
fit <-nls(ydata ~ 1 / (1 + exp((xdata - p1) / p2)), start=list(p1=mean(xdata), p2=-5))
# plot the fit
xr = data.frame(xdata = seq(min(xdata), max(xdata), len=200))
lines(xr$xdata, predict(fit, newdata=xr))
# set all weights to 1, do the fit again; the plot looks identical to the previous one
we = rep(1, length(xdata))
fit2 = nls(ydata ~ 1 / (1 + exp((xdata - p1) / p2)), weights=we, start=list(p1=mean(xdata) ,p2=-5))
lines(xr$xdata, predict(fit2, newdata=xr), col='blue')
# set weight for the data point -30,0.38, and fit again
we[3] = 1000
fit3 = nls(ydata ~ 1 / (1 + exp((xdata - p1) / p2)), weights=we, start=list(p1=mean(xdata), p2=-5))
lines(xr$xdata, predict(fit3, newdata=xr), col='red')
legend('topleft', c('fit without weights', 'fit with weights 1', 'weighted fit for -40,0.38'),
lty=c(1, 1, 1),
lwd=c(2.5, 2.5, 2.5),
col=c('black', 'blue', 'red'))
Run Code Online (Sandbox Code Playgroud)
输出如下所示;如您所见,拟合现在通过所需的数据点(红线):
那么发生了什么:我首先像你一样适合,然后我适合所有权重都设置为 1 的权重;因此,该图看起来与之前的相同,蓝线隐藏了黑线。然后 - 对于fit3- 我将第三个数据点的权重更改为 1000,这意味着现在最小二乘拟合比其他点更“重要”,并且新拟合通过该数据点(红线)。
这也是我更改行的第二个示例
we[3] = 1000
Run Code Online (Sandbox Code Playgroud)
到
we[2] = 1000
Run Code Online (Sandbox Code Playgroud)
这迫使拟合通过第二个数据点:
如果您想获得有关该weights参数的更多信息,可以在此处阅读:文档