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

求R代码计算分类变量各水平的熵、信息增益及水平熵贡献

R实现分类变量的熵、信息增益及水平熵贡献计算

核心逻辑

我们需要实现三个核心功能:

  • 计算单个离散变量的熵
  • 计算分类变量某一水平的熵贡献(即该水平样本占比 × 该水平下目标变量的熵)
  • 批量遍历所有分类变量,计算每个变量的条件熵、信息增益,最终返回全局最低熵值和最高信息增益值

示例数据集

先构造一个包含多水平分类变量和目标变量的示例数据集:

set.seed(123)
df <- data.frame(
  credit = sample(c("excellent", "fair", "poor"), 100, replace = TRUE),
  income = sample(c("low", "medium", "high"), 100, replace = TRUE),
  education = sample(c("high_school", "college", "graduate"), 100, replace = TRUE),
  default = sample(c("yes", "no"), 100, replace = TRUE)  # 用于计算信息增益的目标变量
)

函数实现

1. 单个变量熵计算函数

# 计算离散变量的熵
calc_entropy <- function(x) {
  freq <- table(x) / length(x)
  -sum(freq * log2(freq))
}

2. 单个水平的熵贡献计算函数

该函数计算分类变量某一水平对其整体条件熵的贡献:

# 计算特征某一水平的熵贡献
level_entropy_contribution <- function(data, feature_col, target_col, level) {
  level_data <- data[data[[feature_col]] == level, ]
  p <- nrow(level_data) / nrow(data)  # 该水平的样本占比
  h_level <- calc_entropy(level_data[[target_col]])  # 该水平下目标变量的熵
  p * h_level  # 熵贡献值
}

3. 主函数:批量处理所有分类变量

该函数自动遍历所有分类变量,计算各变量的条件熵、信息增益,以及各水平的熵贡献,最后汇总全局结果:

# 批量计算所有分类变量的熵、信息增益及水平熵贡献
compute_var_entropy_gain <- function(data, target_col) {
  feature_cols <- setdiff(names(data), target_col)
  target_entropy <- calc_entropy(data[[target_col]])
  
  results <- list()
  
  for (col in feature_cols) {
    levels <- unique(data[[col]])
    # 计算每个水平的熵贡献
    level_contributions <- sapply(levels, function(lvl) {
      level_entropy_contribution(data, col, target_col, lvl)
    })
    cond_entropy <- sum(level_contributions)  # 该变量的条件熵
    info_gain <- target_entropy - cond_entropy  # 该变量的信息增益
    
    results[[col]] <- list(
      target_entropy = target_entropy,
      conditional_entropy = cond_entropy,
      information_gain = info_gain,
      level_entropy_contributions = level_contributions
    )
  }
  
  # 提取全局最低条件熵和最高信息增益
  all_cond_entropies <- sapply(results, function(x) x$conditional_entropy)
  all_info_gains <- sapply(results, function(x) x$information_gain)
  
  final_result <- list(
    variable_results = results,
    lowest_conditional_entropy = min(all_cond_entropies),
    highest_information_gain = max(all_info_gains)
  )
  
  return(final_result)
}

使用示例

# 运行主函数
output <- compute_var_entropy_gain(df, target_col = "default")

# 查看单个变量(如credit)的详细结果
output$variable_results$credit

# 查看全局最低条件熵和最高信息增益
cat("最低条件熵值:", output$lowest_conditional_entropy, "\n")
cat("最高信息增益值:", output$highest_information_gain, "\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:15:33