我正在试着复制这篇博客文章。我想探讨样条如何与测试的多项式相比较。
My问题:使用rcs() --受限的三次样条--来自rms包,在常规lm()中应用时得到了非常奇怪的预测。ols()运行良好,但我对这种奇怪的行为感到有点惊讶。有人能向我解释一下发生了什么吗?
library(rms)
p4 <- poly(1:100, degree=4)
true4 <- p4 %*% c(1,2,-6,9)
days <- 1:70
noise4 <- true4 + rnorm(100, sd=.5)
reg.n4.4 <- lm(noise4[1:70] ~ poly(days, 4))
reg.n4.4ns <- lm(noise4[1:70] ~ ns(days,5))
reg.n4.4rcs <- lm(noise4[1:70] ~ rcs(days,5))
dd <- datadist(noise4[1:70], days)
options("datadist" = "dd")
reg.n4.4rcs_ols <- ols(noise4[1:70] ~ rcs(days,5))
plot(1:100, noise4)
nd <- data.frame(days=1:100)
lines(1:100, predict(reg.n4.4, newdata=nd), col="orange", lwd=3)
lines(1:100, predict(reg.n4.4ns, newdata=nd), col="red", lwd=3)
lines(1:100, predict(reg.n4.4rcs, newdata=nd), col="darkblue", lwd=3)
lines(1:100, predict(reg.n4.4rcs_ols, newdata=nd), col="grey", lwd=3)
legend("top", fill=c("orange", "red", "darkblue", "grey"),
legend=c("Poly", "Natural splines", "RCS - lm", "RCS - ols"))你可以看到整个地方都是深蓝色的..。

发布于 2019-10-17 14:46:44
只要指定节点,就可以在非rms安装程序中使用rcs()。预测一个ols对象的缺省值为predict.ols,这很好,因为它“记住”当它符合模型时把结放在哪里。predict.lm没有这个功能,所以它使用新数据集的分布来确定节点的位置,而不是训练数据的分布。
发布于 2020-09-19 07:21:09
将lm与rcs结合使用是个坏主意,即使您在rcs中指定了节点。下面是一个例子:
假数据。
library(tidyverse)
library(rms)
set.seed(100)
xx <- rnorm(1000)
yy <- 10 + 5*xx - 0.5*xx^2 - 2*xx^3 + rnorm(1000, 0, 4)
df <- data.frame(x=xx, y=yy)设置您的环境以使用ols。
ddist <- datadist(df)
options("datadist" = "ddist")拟合lm模型和ols模型。
mod_ols <- ols(y ~ rcs(x, parms=c(min(x), -2, 0, 2, max(x))), data=df)
mod_lm <- lm(y ~ rcs(x, parms=c(min(x),-2, 0, 2, max(x))), data=df)创建测试数据集。
newdf <- data.frame(x=seq(-10, 10, 0.1))比较newdf评分后的模型预测。
preds_ols <- predict(mod_ols, newdata=newdf)
preds_lm <- predict(mod_lm, newdata=newdf)
mean((preds_ols - preds_lm)^2)
as.numeric(coef(mod_ols))
as.numeric(coef(mod_lm))
compare_df <- newdf
compare_df$ols <- preds_ols
compare_df$lm <- preds_lm
compare_df <- compare_df %>%
gather(key="model", value="prediction", -x)
ggplot(compare_df, aes(x=x, y=prediction, group=model, linetype=model)) +
geom_line()模型预测在新的数据上可能是不同的,尽管两个模型之间的系数是相同的。

编辑:
删除对max()和min()的函数调用,在parms参数中解决了这个问题。
kKnots <- with(df, c(min(x), -2, 0, 2, max(x))) ## hard-code
mod_ols <- ols(y ~ rcs(x, parms=kKnots), data=df)
mod_lm <- lm(y ~ rcs(x, parms=kKnots), data=df)https://stackoverflow.com/questions/14633262
复制相似问题