微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 R 对具有求和的复杂函数执行非线性回归?

如何解决如何使用 R 对具有求和的复杂函数执行非线性回归?

我有以下功能

enter image description here

这个函数的参数R是一个常数,值为22.5。我想使用非线性回归(nls() 函数)来估计参数 A 和 B。我做了几次尝试,但都没有成功。我对 R 中的这种类型的操作不是很熟悉,所以我想得到你的帮助。

此外,如果可能,我还想使用 ggplot2 绘制此函数

# Initial data

x <- c(0,60,90,120,180,240)
y <- c(0,0.967676,1.290101,1.327099,1.272404,1.354246)
R <- 22.5

df <- data.frame(x,y)

f <- function(x) (1/(n^2))*exp((-B*(n^2)*(pi^2)*x)/(R^2))

# First try

nls(formula = y ~ A*(1-(6/(pi^2))*sum(f,seq(1,Inf,1))),data = df,start = list(A = 1,B = 0.7))

Error in seq.default(1,1) : 'to' must be a finite number

# Second try

nls(formula = y ~ A*(1-(6/(pi^2))*integrate(f,1,Inf)),B = 0.7))

Error in f(x,...) : object 'n' not found

解决方法

您可以使用有限和近似值。使用 25 个术语:

f <- function(x,B,n = 1:25) sum((1/(n^2))*exp((-B*(n^2)*(pi^2)*x)/(R^2)))
fm <- nls(formula = y ~ cbind(A = (1-(6/pi^2))* Vectorize(f)(x,B)),data = df,start = list(B = 0.7),alg = "plinear")
fm

给予:

Nonlinear regression model
  model: y ~ cbind(A = (1 - (6/pi^2)) * Vectorize(f)(x,B))
   data: df
       B   .lin.A 
-0.00169  1.39214 
 residual sum-of-squares: 1.054

Number of iterations to convergence: 12 
Achieved convergence tolerance: 9.314e-06

模型似乎不太适合数据(下图中的实线);然而,逻辑模型似乎运行良好(虚线)。

fm2 <- nls(y ~ SSlogis(x,Asym,xmid,scal),df)

plot(y ~ x,df)
lines(fitted(fm) ~ x,df)
lines(fitted(fm2) ~ x,df,lty = 2)
legend("bottomright",c("fm","fm2"),lty = 1:2)

screenshot

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。