基于直方图分箱的样本抽取:实现各分箱cable_ind两类样本量均衡
分箱内有线电视标识均衡的数据集抽样方法
现有房产信息数据集包含两个核心字段:
size:房产总单元数cable_ind:是否装有有线电视(0表示无,1表示有)
需对数据集进行抽样处理,使得基于size划分的直方图各分箱中,cable_ind取值为0和1的观测数量完全相等。
示例数据与原始直方图代码
import seaborn as sns import matplotlib.pyplot as plt # 示例数据集 data = { 'size': [10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 30, 30, 40, 40, 50, 50, 60, 60, 60], 'cable_ind': [0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0] } # 绘制带分类的直方图 sns.histplot(data=data, x='size', hue='cable_ind', bins=[10, 20, 30, 40, 50, 60, 70], alpha=.5) # 展示图表 plt.show()
抽样处理方案(适配5万条数据)
针对大规模数据集,使用pandas实现分箱内均衡抽样,核心逻辑是:按分箱分组后,在每个分箱内对cable_ind=0和cable_ind=1的样本取最小数量进行等数抽样。
实现代码
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np # 加载实际数据集(替换为你的数据路径) # df = pd.read_csv('your_real_dataset.csv') # 模拟5万条测试数据 np.random.seed(42) size = np.random.randint(10, 70, 50000) cable_ind = np.random.randint(0, 2, 50000) df = pd.DataFrame({'size': size, 'cable_ind': cable_ind}) # 定义分箱边界(需与直方图分箱保持一致) bins = [10, 20, 30, 40, 50, 60, 70] # 为每条数据标记所属分箱 df['bin'] = pd.cut(df['size'], bins=bins, labels=['10-20', '20-30', '30-40', '40-50', '50-60', '60-70']) # 按分箱和cable_ind统计样本量 bin_group_counts = df.groupby(['bin', 'cable_ind']).size().unstack(fill_value=0) # 存储各分箱抽样结果 sampled_data = [] # 遍历每个分箱做均衡抽样 for bin_label in bin_group_counts.index: count_0 = bin_group_counts.loc[bin_label, 0] count_1 = bin_group_counts.loc[bin_label, 1] # 取两组中的最小数量作为抽样目标 target_num = min(count_0, count_1) if target_num == 0: continue # 分别抽取对应数量的样本 sample_0 = df[(df['bin'] == bin_label) & (df['cable_ind'] == 0)].sample(n=target_num, random_state=42) sample_1 = df[(df['bin'] == bin_label) & (df['cable_ind'] == 1)].sample(n=target_num, random_state=42) sampled_data.extend([sample_0, sample_1]) # 合并所有抽样结果 balanced_df = pd.concat(sampled_data).reset_index(drop=True) # 绘制均衡后的直方图验证效果 sns.histplot(data=balanced_df, x='size', hue='cable_ind', bins=bins, alpha=.5) plt.title('均衡后分箱内有线电视标识分布') plt.show()
关键说明
- 分箱边界必须与直方图的
bins参数完全一致,确保抽样逻辑和可视化逻辑匹配 - 设置
random_state保证抽样结果可复现 - 若某分箱中某类
cable_ind样本量为0,将自动跳过该分箱的抽样
内容的提问来源于stack exchange,提问作者Larry Burholme
相关产品推荐
相关产品推荐

