You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

step_ns未返回预期基函数数量,如何用recipes复现model.matrix效果?

问题原因

你遇到的差异来自两个关键误解:

  1. 参数名错误:splines::ns的节点位置参数是knots,而非k,你在options里传入的k会被直接忽略。
  2. 参数传递方式错误: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 00:08:13