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

如何从mgcv的bam模型te()交互项中提取x1、x2节点位置?

问题:从bam模型的te()张量积交互项提取x1和x2的节点位置

我们使用的示例代码(改编自mgcViz相关文档):

library(mgcViz)  

set.seed(123)
n  <- 10e4
dat <- data.frame("x1" = rnorm(n), "x2" = rnorm(n), "x3" = rnorm(n))
dat$y <- with(dat, sin(x1) + 0.5*x2^2 + 0.2*x3 + pmax(x2, 0.2) * rnorm(n))
b <- bam(y ~ te(x1, x2, k=c(6,9), bs=c("cr","cr")), data = dat, method = "fREML", discrete = TRUE)
b <- getViz(b)
plot(sm(b, 1)) + l_fitRaster() + l_fitContour() + l_points()  

可视化结果:
可视化结果图


解答:可以提取,具体方法如下

拟合后的模型对象(包括getViz()处理后的版本)完整保留了张量积平滑项的参数信息,直接从模型的平滑组件中即可提取x1和x2的节点位置:

  1. 定位到te()对应的平滑项
# 获取模型中的第一个平滑项(即te(x1, x2))
te_smooth <- b$smooth[[1]]
  1. 提取变量对应的节点位置
    可以直接访问平滑项的margin属性:
# x1对应的节点位置
x1_knots <- te_smooth$margin[[1]]$knots

# x2对应的节点位置
x2_knots <- te_smooth$margin[[2]]$knots

也可以用mgcv包的knots()函数实现,写法更简洁:

library(mgcv)

# 提取x1的节点
knots(te_smooth, margin = 1)

# 提取x2的节点
knots(te_smooth, margin = 2)

验证说明:我们在te()中指定了k=c(6,9),提取出的x1节点数为6、x2节点数为9,完全符合设定。

内容的提问来源于stack exchange,提问作者denis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 10:22:22