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

GAM模型部分效应图的坐标轴逆变换方法问询

解决方案

方法1:用mgcv原生plot函数直接处理逆变换

mgcv的plot.gam支持通过trans参数对y轴(部分效应)做逆变换,x轴可以手动替换刻度标签实现逆变换:

# 先定义两个逆变换函数
inv_response <- function(x) exp(x) - 0.006993007  # 响应变量的逆变换
inv_y <- function(x) (exp(x)*900)/10000          # 预测变量y的逆变换

# 绘制s(y)的部分效应图,select=2指定第二个平滑项
plot(BestModel, select = 2,
     trans = inv_response,  # 对y轴(拟合的部分效应)做逆变换
     xlab = "y (原始单位)",
     ylab = "Density (原始单位)")
# 手动替换x轴刻度为逆变换后的值
axis(1, at = axTicks(1), labels = round(inv_y(axTicks(1)), 2))

方法2:用gratia包快速生成逆变换的部分效应图

gratia是mgcv的专属可视化工具,能直接提取平滑项数据并支持变换操作,代码更简洁:

先安装加载包:

install.packages("gratia")
library(gratia)

批量绘制所有逆变换后的部分效应图

draw(BestModel,
     transform = inv_response,  # 统一对响应变量做逆变换
     xlab = c("x (原始单位)", "y (原始单位)", "z (原始单位)"))

单独绘制某一变量(比如y)的逆变换图

# 提取s(y)的平滑项拟合数据
sm_data <- smooth_estimates(BestModel, smooth = "s(y)")

# 对x和y做逆变换
sm_data <- sm_data %>%
  mutate(y_orig = inv_y(y),
         fitted_orig = inv_response(fitted),
         lower_orig = inv_response(lower),
         upper_orig = inv_response(upper))

# 用ggplot绘图,自带置信区间
ggplot(sm_data, aes(x = y_orig, y = fitted_orig)) +
  geom_line(linewidth = 1) +
  geom_ribbon(aes(ymin = lower_orig, ymax = upper_orig), alpha = 0.2) +
  labs(x = "y (原始单位)", y = "Density (原始单位)") +
  theme_minimal()

方法3:手动生成带置信区间的预测数据绘图

如果坚持用自己的新数据集df2,可以同时预测置信区间后再逆变换:

# 预测时获取拟合值和标准误
pred_result <- predict(BestModel, newdata = df2, se.fit = TRUE)

# 对拟合值、置信区间、x变量做逆变换
df2 <- df2 %>%
  mutate(fit_orig = inv_response(pred_result$fit),
         lower_orig = inv_response(pred_result$fit - 1.96*pred_result$se.fit),
         upper_orig = inv_response(pred_result$fit + 1.96*pred_result$se.fit),
         y_orig = inv_y(y))

# ggplot绘图
ggplot(df2, aes(x = y_orig, y = fit_orig)) +
  geom_line() +
  geom_ribbon(aes(ymin = lower_orig, ymax = upper_orig), alpha = 0.2) +
  labs(x = "y (原始单位)", y = "Density (原始单位)")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 23:20:15