如何解决如何做指数回归模型?
我想在 R 中获得指数回归。
我使用的命令是:
regression <- read.delim("C:/Users/david/OneDrive/Desktop/regression.txt")
View(regression)
source('~/.active-rstudio-document',echo=TRUE)
m <- nls(DelSqRho ~ (1-exp(-a*(d-b)**2)),data=regression,start=list(a=1,b=1))
y_est<-predict(m,regression$d)
plot(x,y)
lines(x,y_est)
summary(m)
但是,当我运行它时,出现错误:
Error in nls(DelSqRho ~ (1 - exp(-a * (d - b)^2)),data = regression,:
step factor 0.000488281 reduced below 'minFactor' of 0.000976562
解决方法
nls
对起始参数的值非常敏感,因此您希望选择能够合理拟合数据的值(minpack.lm::nlsLM
可能更宽容一些)。
您可以在 a=1
和 b=1
的起始值处绘制曲线,并发现它不能很好地捕捉曲线。
regression <- read.delim("regression.txt")
with(regression,plot(d,DelSqRho,ylim=c(-3,1)))
xs <- seq(min(regression$d),max(regression$d),length=100)
a <- 1; b <- 1; ys <- 1 - exp(-a* (xs - b)**2)
lines(xs,ys)
获得起始值的一种方法是重新排列目标函数。
y = 1 - exp(-a*(x-b)**2)
可以重新排列为 log(1/(1-y)) = ab^2 - 2abx + ax^2
(此处 y
必须小于 1)。然后可以使用线性回归来估计 a
和 b
。
start_m <- lm(log(1/(1-DelSqRho)) ~ poly(d,2,raw=TRUE),regression)
unname(a <- coef(start_m)[3]) # as `a` is aligned with the quadratic term
# [1] -0.2345953
unname(b <- sqrt(coef(start_m)[1]/coef(start_m)[3]))
# [1] 2.933345
(有时无法以这种方式重新排列数据,您可以尝试通过绘制各种起始参数的曲线来粗略了解参数。nls2
也可以进行暴力搜索或对起始参数进行网格搜索。)
我们现在可以尝试在这些参数下估计 nls
模型:
m <- nls(DelSqRho ~ 1-exp(-a*(d-b)**2),data=regression,start=list(a=a,b=b))
coef(m)
# a b
# -0.2379078 2.8868374
并绘制结果:
# note that `newdata` must be a named list or data frame
# in which to look for variables with which to predict.
y_est <- predict(m,newdata=data.frame(d=xs))
with(regression,DelSqRho))
lines(xs,y_est,col="red",lwd=2)
拟合不太好,可能暗示需要更灵活的模型。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。