小样本下mgcv::gam模拟geom_smooth gam拟合效果的技术问询
问题描述
我正在针对每个唯一XY配对(本次共2组,每组仅11个观测值)运行mgcv::gam模型。理想情况下,当A=0时,B的预测值应在1000到2000之间,但当前模型预测值约为450。
已尝试的方案:
- 调整
mgcv::gam的参数k、样条类型 - 使用形状约束加性模型(但在大数据集上处理缓慢,且不满足假设时失效)
核心需求:
- 希望
mgcv::gam能达到ggplot中geom_smooth(method = "gam")的拟合效果,已知geom_smooth的gam会为绘图生成合成观测值而非使用原始数据 - 在不生成人工/合成数据的前提下,找到最佳近似
geom_smooth拟合效果的方法 - 接受其他模型类型、样条函数等方案,但扩展后的数据集不保证单调性/直接关系
- 方案需简洁,可配合
summarise使用,且能灵活适配其他XY配对 - 所有场景中,对接近0的A值赋予更高权重可能会有帮助
编辑补充:
实际上,采用分段方式连接组内点的样条函数可能更理想。若能以分段方式连接点,可能无需建模。理论上splinefun是解决方案,因为它应能穿过数据点,但实际并未生效。
代码示例
加载包与数据
# packages library(sf) library(reshape2) library(dplyr) library(tidyr) library(data.table) library(stringr) library(zoo) library(ggplot2) library(mgcv) library(scam) library(npreg) library(cgam) library(dtplyr) library(collapse) library(lubridate) library(purrr) # reading in data DF <- structure(list(X = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), Y = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4), grp = c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"), A = c(6.1513671875, 4.8748779296875, 3.40283203125, 1.9866943359375, 1.1297607421875, 0, 0, 0, 0, 0, 0, 0, 6.0810546875, 4.8055419921875, 3.33447265625, 1.9195556640625, 1.065185546875, 0, 0, 0, 0, 0, 0, 0), B = c(10000, 7500, 5000, 3000, 2000, 1000, 800, 600, 400, 200, 100, 50, 10000, 7500, 5000, 3000, 2000, 1000, 800, 600, 400, 200, 100, 50)), row.names = c(NA, -24L), class = c("tbl_df", "tbl", "data.frame"))
当前GAM模型实现
# running model over XY pairings DF_dat <- DF %>% summarise(gam_model=list(gam(B~s(A,bs="cs",fx=TRUE,k=6))), .by = c(X,Y)) # predicting B for A = 0 pred_df <- data.frame(A=0) gam_predict <- function(m) predict(m,pred_df) DF_dat$gam_pred_0 <- sapply(DF_dat$gam_model,gam_predict)
尝试的样条函数实现
models <- DF %>% summarise(spline_fun=list(splinefun(A, B)), .by = c(X,Y)) models$spline_pred_0 <- sapply(models$spline_fun, function(x) x(0))
内容的提问来源于stack exchange,提问作者user11057680
相关产品推荐
相关产品推荐

