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

如何实现函数检测Counter中元素占比是否相近?

检测Counter元素占比是否相近(训练集标签平衡检测)

直接用以下函数实现需求,核心思路是通过对比占比的最大值与最小值的绝对差,结合math.isclose的abs_tol参数判断所有元素占比是否相近:

import math
from collections import Counter

def are_labels_balanced(counter, abs_tol=2):
    total = sum(counter.values())
    if total == 0:
        return True  # 空数据集默认平衡,可根据实际需求调整
    percents = [count / total * 100 for count in counter.values()]
    if len(percents) <= 1:
        return True
    max_p = max(percents)
    min_p = min(percents)
    return math.isclose(max_p, min_p, abs_tol=abs_tol)

测试示例

# 原示例:占比60%、20%、20%,不相近
c1 = Counter(["Dog", "Cat", "Dog", "Horse", "Dog"])
print(are_labels_balanced(c1))  # 输出: False

# 平衡示例:三类各占约33.33%
c2 = Counter(["Dog","Cat","Horse","Dog","Cat","Horse"])
print(are_labels_balanced(c2))  # 输出: True

# 两类各占50%,完全平衡
c3 = Counter(["A","A","B","B"])
print(are_labels_balanced(c3))  # 输出: True

# 两类占比60%、40%,差值超2%
c4 = Counter(["A","A","A","B","B"])
print(are_labels_balanced(c4))  # 输出: False

逻辑说明

  1. 先计算总样本数,避免除以0的异常情况
  2. 生成每个元素的占比百分比列表
  3. 若只有1类标签或无样本,直接判定为平衡
  4. 通过对比占比的最大值和最小值,利用math.isclose判断两者的绝对差是否在允许的公差范围内——只要最大最小占比满足条件,所有元素的占比必然彼此相近

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:10:38