step_ns未返回预期基函数数量,如何用recipes复现model.matrix效果?
问题原因
你遇到的差异来自两个关键误解:
- 参数名错误:
splines::ns的节点位置参数是knots,而非k,你在options里传入的k会被直接忽略。 - 参数传递方式错误:
step_ns本身提供了knots和boundary_knots专用参数,无需将这两个参数打包进options,直接传入更直观且不易出错。
之前的代码中,因为k参数不被识别,step_ns使用了默认的deg_free=2,所以仅生成2列样条基。
解决代码
要复现model.matrix的行为(包含截距的19列结果),可以这样写:
library(recipes) library(dplyr) d <- tibble(x = seq(-2, 2, 0.01)) # 使用step_ns的专用参数传递节点,同时添加截距列 recipe(~., data=d) %>% step_ns(x, knots = seq(-1, 1, 0.125), boundary_knots = c(-1.5, 1.5)) %>% step_intercept() %>% # 对应model.matrix中~公式自动添加截距的行为 prep %>% bake(new_data=d) %>% ncol # [1] 19
如果只需要样条基(不含截距,对应splines::ns的原生输出),去掉step_intercept()即可:
recipe(~., data=d) %>% step_ns(x, knots = seq(-1, 1, 0.125), boundary_knots = c(-1.5, 1.5)) %>% prep %>% bake(new_data=d) %>% ncol # [1] 18
内容的提问来源于stack exchange,提问作者Demetri Pananos
相关产品推荐
相关产品推荐

