使用基本 R 包将非线性方程拟合到数据

问题描述

假设我有以下数据

Data = structure(list(col1 = c(31,66,88,123,249,362,488,610,730,842),col2 = c(2101.58953918969,2103.57391509821,2100.3292541732,2101.64107993765,2100.51743895393,2100.16708521627,2102.1992412748,2101.06516854423,2101.87929065226,2101.25318636023)),row.names = c(NA,-10L),class = "data.frame")

现在我想拟合一个非线性方程如下 -

library(stats)
nls(col2 ~ x1 + x2 / (1 + exp(-x3 * (col1 - x4))),data = Data,start = list(x1 = 0,x2 = 0,x3 = 0,x4 = 0),algorithm = "plinear")

但是有了这个我得到以下错误 -

Error in qr.qty(QR.rhs,.swts * ddot(attr(rhs,"gradient"),lin)) : 
  NA/NaN/Inf in foreign function call (arg 5)

你能帮我理解我的方法出了什么问题吗?

我只想使用基本包来拟合这个方程,因为我无法在我的系统中从 Internet 下载任何贡献的包。

任何指针都将受到高度赞赏。

解决方法

有几个问题:

  1. 当使用 plinear 时,右侧应该是一个矩阵,使得该矩阵的第 i 列乘以线性输入的第 i 个参数,并且这些线性参数不应具有起始值。线性参数将报告为 .lin1 和 .lin2
  2. 需要更好的非线性参数起始值。
nls(col2 ~ cbind(1,1 / (1 + exp(-x3 * (col1 - x4)))),data = Data,start = list(x3 = sd(Data$col1),x4 = mean(Data$col1)),algorithm = "plinear")

给予:

Nonlinear regression model
  model: col2 ~ cbind(1,1/(1 + exp(-x3 * (col1 - x4))))
   data: Data
       x3        x4     .lin1     .lin2 
 295.3813  358.9000 2101.5302   -0.2175 
 residual sum-of-squares: 9.145

Number of iterations to convergence: 0 
Achieved convergence tolerance: 0
,

如果我对您当前的数据使用 SSfpl,我可以得到答案。

n1 <- nls(col2 ~ SSfpl(col1,A,B,m,s),data=Data)

pframe <- data.frame(col1=seq(0,900,length=101))
pframe$col2 <- predict(n1,newdata=pframe)

library(ggplot2); theme_set(theme_bw())
ggplot(Data,aes(col1,col2)) + geom_point() + geom_smooth() +
  geom_line(data=pframe,colour="red")

data,loess curve + CI,and fitted four-parameter logistic

参数化和你的不太一样:

         A          B          m          s 
2001.56354 2002.06645  642.30178   20.76013 

基于x1 + x2 / (1 + exp(-x3 * (col1 - x4)))

我相信 x4 = m(中点),x3 = s(比例),x1 = A(左渐近线),和 x2 = B-AB 是右渐近线)。