r - 从 R 的 b 样条 bs() 函数中找到分段多项式系数
问题描述
我正在编写一个(更大的)数据分析和绘图程序,我不需要详细介绍。我使用的数据集是自 2004 年以来全球“人工智能”一词的谷歌趋势。这给出了两列;自 2004 年以来的几个月和搜索兴趣水平。我正在尝试从内置 b 样条函数 bs 中提取分段多项式,因为它们是绘制它们所必需的。具体来说,我一直在使用李哲元编写的 R 库 SplinesUtils 并在此处引用,另一个 stackOverflow 线程。
我的问题是没有让包工作或使用函数,这是所谓的正确工作函数似乎没有给我准确的多项式。这就是我认为的原因: 谷歌趋势数据图片 R 中的给定多项式 在desmos中绘制的那些多项式 您可以看到生成的多项式似乎与数据不匹配。显然我没有添加边界,但无论如何它们都应该与数据非常接近。
我已通过电子邮件向图书馆的创建者发送电子邮件并解释了我的问题。但是我不完全确定这是库的问题,更多的是我对 bs() 函数的使用。我把 x 和 y 弄错了吗?语法是否有点不正确?是的,我是 R 和样条线的新手,所以我不确定这一切。
我从 google 下载了数据并将其命名为 AIData.csv,但我不确定如何托管它,以便任何回答这个问题的人都可以查看,所以我将其放入 pastebin 中。https://pastebin.com/itQcWWSg
library(SplinesUtils)
pyin <- c("AIData.csv","the directory you save this R file in (which should also have AIData.csv in it)")
setwd <- pyin[2]#sets working directory to the above string
csvfile <- read.csv(file=pyin[1],header=TRUE)#reads the csv file into a dataframe with headers
names(csvfile) <- c("months","searchInterest")#renames the headers becuase they're very long and cause formatting issues
model <- lm(csvfile$searchInterest ~ bs(csvfile$months, df=5))#a linear model of months against a bspline of search interest
piecewisePoly <- RegBsplineAsPiecePoly(model, "bs(csvfile$months, df = 5)",shift=FALSE)#creates the piecewise polynomials
piecewisePoly
piecewisePoly$PiecePoly$coef
我预计分段多项式与谷歌搜索趋势图大致相同。它没有;请参阅上面的desmos链接。运行上述代码的直接输出是这样的:
Loading required package: splines
3 piecewise polynomials of degree 3 are constructed!
Use 'summary' to export all of them.
The first 3 are printed below.
3.1 - 3.14 * x - 0.047 * x ^ 2 - 0.000246 * x ^ 3
-34.5 - 1.16 * x - 0.0123 * x ^ 2 - 4.27e-05 * x ^ 3
-544 + 12.3 * x + 0.107 * x ^ 2 + 0.00031 * x ^ 3
[,1] [,2] [,3]
[1,] 3.0953478761 -3.448227e+01 -5.435058e+02
[2,] -3.1420823054 -1.164313e+00 1.234959e+01
[3,] 0.0469800796 1.228237e-02 -1.073097e-01
[4,] -0.0002456503 -4.273970e-05 3.100391e-04
[Finished in 0.7s]
解决方案
李哲元回复了我的邮件,做了一些澄清。我会在下面为任何有相同查询的人发布它。
" 您忘记了 model$coefficients[1] 中的模型截距。您需要将此截距添加到每个分段多项式以恢复拟合值。您可以使用
finalcoef <- piecewisePoly$PiecePoly$coef
finalcoef[1, ] <- finalcoef[1, ] + model$coefficients[1]
finalcoef
我认为这是包中最令人困惑的部分:报告的样条不是拟合值。我在 ?RegBsplineAsPiecePoly 下的示例中仅微弱地提到了这一点,其方式可能还不够清楚。"
推荐阅读
- php - 处理 PHP 数组时截断的结果
- node.js - 访问 MongoDB 子文档中的文档
- javascript - 如何将数据直接放入剪贴板?(Ruby on Rails 或 JS)
- android - android:Theme.Material.Light.DarkActionBar 和 Theme.AppCompat.Light.DarkActionBar 的区别
- javascript - jQuery 事件范围不起作用
- sas - SAS Proc SQL 非常慢
- javascript - 为什么这个控制台记录两次?
- excel - 放置属性 OLEObject
- java - 打字稿:如何一次请求上传多张图片?
- while-loop - 如何在 SAS 中正确使用 while 循环