本文介绍了使用自然样条拟合进行预测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的自然样条曲线(df = 3)模型,我正在尝试从样本观察中预测一些.使用功能predict()
,我能够获得样本中观测值的拟合值,但无法获得新观测值的预测值.
I have a fitted a simple natural spline (df = 3) model and I'm trying to predict for some out of sample observations. Using the function predict()
, I'm able to get fitted values for in-sample observations but I've not been able to get the predicted value for new observations.
这是我的代码:
library(splines)
set.seed(12345)
x <- seq(0, 2, by = 0.01)
y <- rnorm(length(x)) + 2*sin(2*pi*(x-1/4))
# My n.s fit:
fit.temp <- lm(y ~ ns(x, knots = seq(0.01, 2, by = 0.1)))
# Getting fitted values:
fit.temp.values <- predict(fit.temp,interval="prediction", level = 1 - 0.05)
# Plotting the data, the fit, and the 95% CI:
plot(x, y, ylim = c(-6, +6))
lines(x, fit.temp.values[,1], col = "darkred")
lines(x, fit.temp.values[,2], col = "darkblue", lty = 2)
lines(x, fit.temp.values[,3], col = "darkblue", lty = 2)
# Consider the points for which we want to get the predicted values:
x.new <- c(0.275, 0.375, 0.475, 0.575, 1.345)
如何获取x.new的预测值?
How can I get the predicted values for x.new?
非常感谢您的帮助,
p.s.我在SO上搜索了所有相关问题,但没有找到答案.
p.s. I searched all related questions on SO and I didn't find the answer.
推荐答案
使用称为x
的列创建数据框,并将其作为newdata
参数传递给predict
:
Create a data frame with a column called x
, and pass it as the newdata
argument to predict
:
predict(fit.temp, newdata=data.frame(x=x.new))
这篇关于使用自然样条拟合进行预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!