在 RI 中,使用 nls 进行非线性最小二乘拟合。那么如何使用拟合提供的系数值绘制模型函数呢?
(是的,这是来自 R 相对新手的一个非常幼稚的问题。)
使用?nls
我逐行指出的示例中的第一个示例并遵循示例,可以实现以下目标:
#This is just our data frame
DNase1 <- subset(DNase, Run == 1)
DNase1$lconc <- log(DNase1$conc)
#Fit the model
fm1DNase1 <- nls(density ~ SSlogis(lconc, Asym, xmid, scal), DNase1)
#Plot the original points
# first argument is the x values, second is the y values
plot(DNase1$lconc,DNase1$density)
#This adds to the already created plot a line
# once again, first argument is x values, second is y values
lines(DNase1$lconc,predict(fm1DNase1))
参数的predict
方法nls
是自动返回拟合y
值。或者,您添加一个步骤并执行
yFitted <- predict(fm1DNase1)
并将yFitted
第二个参数传递给lines
。结果如下所示:
或者如果你想要一个“平滑”的曲线,你所做的就是简单地重复这个但在更多点上评估函数:
r <- range(DNase1$lconc)
xNew <- seq(r[1],r[2],length.out = 200)
yNew <- predict(fm1DNase1,list(lconc = xNew))
plot(DNase1$lconc,DNase1$density)
lines(xNew,yNew)
coef(x) 返回回归结果 x 的系数。
model<-nls(y~a+b*x^k,my.data,list(a=0.,b=1.,k=1))
plot(y~x,my.data)
a<-coef(model)[1]
b<-coef(model)[2]
k<-coef(model)[3]
lines(x<-c(1:10),a+b*x^k,col='red')
例如。
我知道你想要什么(我是科学家)。不是这样,但至少展示了如何使用“曲线”在任何范围内绘制拟合函数,并且曲线将是平滑的。使用与上述相同的数据集:
nonlinFit <- nls(密度 ~ a - b*exp(-c*conc), data = DNase1, start = list(a=1, b=1, c=1) )
fitFnc <- function(x) predict(nonlinFit, list(conc=x))
曲线(fitFnc,从=.5,到=10)
或者,
曲线(fitFnc,从=8.2,到=8.4)
或者,
curve(fitFnc, from=.1, to=50) # 远远超出数据范围
或其他任何东西(没有先设置一系列评估点)。
我是一名初级 R 程序员,所以我不知道如何(优雅地)在 Mathematica 中实现像 ReplaceAll ( /. ) 之类的东西,人们可以用它来用拟合参数替换模型中符号参数的出现。这第一步虽然看起来很糟糕,但仍然有效:
myModel <- “a - b*exp(-c*conc)”
nonlinFit <- nls(as.formula(paste("密度 ~", myModel)), data = DNase1, start = list(a=1, b=1, c=1) )
它为您留下了一个单独的“模型”(作为字符串),您可以使用拟合参数......干净利落地(不挖掘 a、b、c)只需使用 nonlinFit ...不知道如何。
函数“曲线”将为您绘制函数。