R中使用recipes包归一化的数值变量如何还原为原始取值
Z-score归一化阈值反推原始值方案
你使用的step_center+step_scale是标准Z-score归一化,对应的反变换公式为:原始值 = 归一化后的值 × 对应变量标准差 + 对应变量均值recipes的预处理对象已经存储了所有数值变量的训练集均值、标准差参数,直接提取参数代入公式即可完成转换。
具体实现步骤
1. 提取年龄变量的归一化参数
两种常用提取方式二选一即可:
方式1:通过step类型识别提取(推荐,无需依赖字符串匹配)
library(purrr) # 提取中心化step的均值参数 center_step <- recipe_obj$steps[[map_lgl(recipe_obj$steps, ~inherits(.x, "step_center"))]] age_mean <- center_step$means["age"] # 此处"age"替换为你数据集中年龄变量的实际列名 # 提取标准化step的标准差参数 scale_step <- recipe_obj$steps[[map_lgl(recipe_obj$steps, ~inherits(.x, "step_scale"))]] age_sd <- scale_step$sds["age"] # 同样替换为年龄实际列名
方式2:通过step id匹配提取
library(stringr) age_mean <- recipe_obj$steps[[which(sapply(recipe_obj$steps, function(x) str_detect(x$id, "center")))]]$means["age"] age_sd <- recipe_obj$steps[[which(sapply(recipe_obj$steps, function(x) str_detect(x$id, "scale")))]]$sds["age"]
2. 反算归一化阈值对应的原始年龄值
代入反变换公式即可得到有实际含义的阈值:
# 示例:将决策树输出的归一化阈值1.5转换为原始年龄 scaled_threshold <- 1.5 original_threshold <- scaled_threshold * age_sd + age_mean
如果计算得到original_threshold为50,那么决策树的拆分规则>1.5即对应原始年龄>50岁,<1.5对应原始年龄≤50岁。
批量转换多个阈值
如果需要一次性转换多个归一化阈值,直接做向量化运算即可:
scaled_thresholds <- c(-1.5, 0, 1.2, 2) original_thresholds <- scaled_thresholds * age_sd + age_mean
内容的提问来源于stack exchange,提问作者Wisit C
相关产品推荐
相关产品推荐

