在R中拟合抛物线时的误差

时间:2015-01-04 16:13:15

标签: r

我试图将抛物线拟合到R中的数据中 我已经在MATLAB中创建了拟合(所以我知道参数值),但是当我运行这段代码时:

library("nls2")
fo <- y ~ A * (x ^ 2) + B * x + C
sA <- seq(-.000001,0,len=10)
sB <- seq(0,.001,len=10)
sC <- seq(1,20,len=10)

st1 <- expand.grid(A=sA,B=sB,C=sC)
mod1 <- nls2(fo,start=st1,algorithm="brute-force")
z <- nls(fo,start=coef(mod1))

x <- c(50072,50072,52536,52536,53768,53768,53768,54384,54384,54384, 54384,54692,54692,54846,54846,54846,54846,54846,54923,54923, 54923,54923,54923,54923,54961.5,54961.5,54961.5,54961.5,54961.5,54961.5,55000,55‌​000,55000) 
y <- c(0.46007,0.47185,0.24377,0.28506,0.16560,0.13587,0.16844, 0.08156,0.06917,0.09357,0.08704,0.02968,0.03293,0.01233,0.01509, 0.01095,0.005,0.00704,0.00861,0.00287,0.00456,0.01043,0.00373,0.00594, 0.00628,0.00089,0.00085,0.00055,0.00142,0.0022,-0.00091,-0.00209,-0.00293)

我得到以下内容: ž

           A             B             C 
-7.728222e-09  7.177715e-04 -1.610196e+01 
> z
Nonlinear regression model
  model: y ~ A * (x^2) + B * x + C
   data: parent.frame()
         A          B          C 
-7.728e-09  7.178e-04 -1.610e+01 
 residual sum-of-squares: 0.0106

Number of iterations to convergence: 1 
Achieved convergence tolerance: 4.457e-07

但是confint(z)给了我以下错误消息:

Waiting for profiling to be done...
Error in approx(sp$y, sp$x, xout = cutoff) : 
  need at least two non-NA values to interpolate

出了什么问题?谢谢!

1 个答案:

答案 0 :(得分:2)

由于您的模型是线性的,因此您应该使用lm

x <- 1:100
set.seed(42)
y <- 20 * (x - 30)^2 + 4 + rnorm(100)

fit <- lm(y ~ poly(x, degree = 2, raw = TRUE))
confint(fit)
#                                       2.5 %     97.5 %
#(Intercept)                      18003.63406 18004.9075
#poly(x, degree = 2, raw = TRUE)1 -1200.04169 -1199.9835
#poly(x, degree = 2, raw = TRUE)2    19.99984    20.0004

nls相比,这并不是使用数字优化器,而是计算&#34;精确&#34;溶液

FYI:如果非线性在参数中,则模型被认为是非线性的。 y ~ a * x^2 + b * x + c是线性的(在参数中),但是,例如,y ~ sin(a - x)不是。