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

R语言recipes包中是否存在Robust Scaler方法?

在R的recipes包中是否有Robust Scaler方法?

目前recipes包里并没有内置的Robust Scaler(基于中位数和四分位距的特征缩放方法)。

如果需要实现这一功能,可以通过自定义步骤来完成,以下是一个可直接使用的示例:

library(recipes)

# 定义自定义Robust Scaler步骤
step_robust_scaler <- function(recipe, ...) {
  terms <- ellipse_check(...)
  add_step(
    recipe,
    step_robust_scaler_new(
      terms = terms,
      trained = FALSE,
      medians = NULL,
      iqrs = NULL,
      role = "predictor",
      skip = FALSE,
      id = rand_id("robust_scaler")
    )
  )
}

step_robust_scaler_new <- function(terms, trained, medians, iqrs, role, skip, id) {
  step(
    subclass = "robust_scaler",
    terms = terms,
    trained = trained,
    medians = medians,
    iqrs = iqrs,
    role = role,
    skip = skip,
    id = id
  )
}

prep.step_robust_scaler <- function(x, training, info = NULL, ...) {
  col_names <- terms_select(x$terms, info = info)
  # 计算训练集的中位数和四分位距
  x$medians <- apply(training[, col_names], 2, median)
  x$iqrs <- apply(training[, col_names], 2, IQR)
  x$trained <- TRUE
  x
}

bake.step_robust_scaler <- function(object, new_data, ...) {
  col_names <- names(object$medians)
  # 应用缩放:(值 - 中位数) / 四分位距
  for (col in col_names) {
    new_data[[col]] <- (new_data[[col]] - object$medians[col]) / object$iqrs[col]
  }
  new_data
}

# 使用示例
data(iris)
# 创建配方并添加自定义Robust Scaler步骤
iris_rec <- recipe(Species ~ ., data = iris) %>%
  step_robust_scaler(all_predictors()) %>%
  prep(training = iris)

# 应用到数据
scaled_iris <- bake(iris_rec, new_data = iris)

你也可以根据需求调整缩放逻辑(比如是否除以1.349将四分位距转换为正态分布等价标准差),核心是通过自定义step来弥补recipes包的这一缺失功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:45:47