首页 > 解决方案 > 使用 cob 包通过特定点进行约束曲线拟合时出错:外部函数调用中的 NA/NaN/Inf

问题描述

我试图通过一组给定的点找到最佳拟合曲线。拟合曲线也必须通过这些点。我在 Cross Validated 上找到了建议使用该软件包的答案。cobs: Constrained B-Splines (Sparse Matrix Based)但是,在使用示例数据对其进行测试时出现错误:

Error in x %*% coefficients: NA/NaN/Inf in foreign function call (arg 2)  

我的问题:是什么导致了这个错误,我该如何解决?我也对使用不同方法/包的其他解决方案持开放态度。谢谢!

library(cobs)

dat <- data.frame(
  x = c(1e-06,0.25,0.5,0.75,1,2,3,4,5,6),
  y = c(1e-07,1.925,2.9625,3.469375,
        3.875,4.5315,4.89,5.09375,5.216,5.46))
dat
#>          x         y
#> 1  1.0e-06 0.0000001
#> 2  2.5e-01 1.9250000
#> 3  5.0e-01 2.9625000
#> 4  7.5e-01 3.4693750
#> 5  1.0e+00 3.8750000
#> 6  2.0e+00 4.5315000
#> 7  3.0e+00 4.8900000
#> 8  4.0e+00 5.0937500
#> 9  5.0e+00 5.2160000
#> 10 6.0e+00 5.4600000

# visual inspection
plot(dat); lines(dat)

# define constrained points
con <- matrix(
  cbind(c(0,0,0,0,0,0,0,0,0,0),
        c(1e-06,0.25,0.5,0.75,1,2,3, 4,5,6),
        c(1e-07,1.925,2.9625,3.469375,
          3.875,4.5315,4.89,5.09375,5.216, 5.46)), 
  ncol = 3, nrow = 10)

# curve fitting 
fit_result <- cobs(dat$x, dat$y, pointwise = con)
#> qbsks2():
#>  Performing general knot selection ...
#> Error in x %*% coefficients: NA/NaN/Inf in foreign function call (arg 2)

reprex 包(v0.3.0)于 2020 年 1 月 21 日创建

标签: rconstraintsregressioncurve-fittingspline

解决方案


您的问题听起来像“样条插值”。

可能是 R 中最简单的解决方案:

f = splinefun(dat$x, dat$y)

#simple plot
x = seq(0, 6, , 200)
plot(dat)
lines(x, f(x))

我注意到有不同类型的曲线拟合。例如,在回归建模中,目标通常是找到一条线或平面(泛化为曲面),以提供最佳拟合。样条拟合和回归建模并不总是分开进行,因为在某些情况下样条用于回归目的。

注意:我在 R 帮助上发帖,并被要求在此处发帖。


推荐阅读