在R中使用nls()进行曲线拟合

4

我有一些数据,需要用某个公式拟合曲线。

为了做到这一点,我使用nls函数,如下所示:

fitmodel <- nls(y ~ a+b/(1+exp(-((x-c)/d))),
    data = combined,
    start=list(a=200,b=2000, c=80, d=10.99),      
    trace=TRUE)

这个代码可以运行,但是会有以下警告:

"1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf"

当我在图中绘制带有确定参数的函数时,它完全不符合要求,就像这样:

jpw <- coef(fitmodel)

logfit <- function(x,jpw) {jpw[1] + jpw[2]/(1+exp(-((x-jpw[3])/jpw[4])))
}

points(logfit(x, jpw),type='l')

不好的匹配

我的朋友试图在另一个程序中拟合这些数据。它找到了相同的参数,并且另一个程序绘制的函数完美地拟合了这些数据。 此外,手动查找可以很容易地找到使曲线与数据良好匹配的参数。

我错在哪里了?我是初学者,所以可能是一些愚蠢的错误。

谢谢您提前!

已编辑:数据文件


1
这可能是与您的数据combined有关的问题。它是否包含数字变量xy - Andrew Gustar
通常当您在空向量上调用min/max时会出现此错误,这种情况通常发生在访问数据帧的列时出错。正如安德鲁上面提到的那样,请检查您的数据是否包含所有必需的列。 - jeremycg
我赋值x和y y <- mM1$V1 x <- mM1$V3数据看起来像这样: V1 V2 V3 测量值 样本 小时(从0到238,每0.5个小时)我在上面的原始帖子中包含了一张屏幕截图。 - jpw
2个回答

2

你的问题在于绘图时只给了一个值,所以它将其作为y,并默认x轴上的一个单位为一个值(如果您查看原始图,您会发现它在439处结束,这是您拥有的点数)。

您可以通过同时使用x和y来解决此问题:

plot(combined$V1~combined$V3)
points(x,logfit(x,jpw), type = 'l')

enter image description here


1

很想看看你的数据集。
无论如何,这是一个可行的例子。希望能对你有所帮助。

logfit <- function(x,jpw) {
   jpw[1] + jpw[2]/(1+exp(-((x-jpw[3])/jpw[4])))
}

jpw <- c(-2,1,0,.5)
x <- runif(100, -3, 3)
y <- logfit(x, jpw)+rnorm(100, sd=0.01)
df <- data.frame(x,y)

curve(logfit(x,jpw),from=-3,to=3, ,type='l')
points(x,y)

enter image description here

fitmodel <- nls(y ~ a + b/(1+exp(-((x-c)/d))),
    data = df,
    start=list(a=1, b=2, c=1, d=1),      
    trace=TRUE)

fitmodel

输出结果为:

Nonlinear regression model
  model: y ~ a + b/(1 + exp(-((x - c)/d)))
   data: df
        a         b         c         d 
-1.999901  1.002425  0.006527  0.498689 
 residual sum-of-squares: 0.009408

Number of iterations to convergence: 6 
Achieved convergence tolerance: 1.732e-06

这里我使用@jpw提供的数据。
df <- dget(file="data.txt")
names(df) <- c("y","v2","x")    
fitmodel <- nls(y ~ a + b/(1+exp(-((x-c)/d))),
    data = df,
    start=list(a=200,b=2000, c=80, d=10.99),      
    trace=TRUE)
summary(fitmodel)

估计的参数为:

Formula: y ~ a + b/(1 + exp(-((x - c)/d)))

Parameters:
   Estimate Std. Error t value Pr(>|t|)    
a  231.6587     2.8498   81.29   <2e-16 ***
b 1893.0646     6.3528  297.99   <2e-16 ***
c  151.5405     0.2016  751.71   <2e-16 ***
d   17.2068     0.1779   96.72   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 37.19 on 473 degrees of freedom

Number of iterations to convergence: 10 
Achieved convergence tolerance: 3.9e-06

现在我绘制结果。

plot(df$x, df$y)
jpw.est <- coef(fitmodel)
curve(logfit(x,jpw.est), from=0, to=300, col="red", lwd=2, add=T)

enter image description here


这个数据集我该如何向您展示呢?谢谢! - jpw
x和y被分配到V1和V3上。 感谢提示,已进行编辑;希望上传成功并且可访问。 - jpw
太棒了!非常感谢! - jpw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接