【发布时间】:2021-09-24 17:00:12
【问题描述】:
我正在尝试使用WeightedRandomSampler 处理数据集中的不平衡(class1:2555,class 2:227,class 3:621,class 4:2552 图像)。但是,我调试了这些步骤,但它背后的直觉对我来说并不清楚。我的目标标签采用 one-hot 编码向量的形式,如下所示。
train_labels.head(5)
我将标签转换为类索引:
labels = np.argmax(train_labels.loc[:, 'none':'both'].values, axis=1)
train_labels = torch.from_numpy(labels)
train_labels
tensor([0, 0, 1, ..., 1, 0, 0])
以下是我用来计算加权随机采样器的步骤。如果我对任何步骤的解释有误,请纠正我。
-
统计数据集中每个类的样本数
class_sample_count = np.array(train_labels.value_counts()) class_sample_count array([2555, 2552, 621, 227]) -
计算每个类的权重
weight = 1. / class_sample_count weight array([0.00039139, 0.00039185, 0.00161031, 0.00440529]) -
计算数据集中每个样本的权重。
samples_weight = np.array(weight[train_labels]) print(samples_weight[1], samples_weight[2] ) 0.0003913894324853229 0.00039184952978056425
将 np.array 转换为张量
tensor([0.0004, 0.0004, 0.0004, ..., 0.0004, 0.0004, 0.0004],
dtype=torch.float64)
转换为张量后,所有样本在所有四个条目中似乎都具有相同的值?那么加权随机抽样是如何帮助处理不平衡数据集的呢?
我将不胜感激。谢谢。
【问题讨论】: