关于pytorch处理类别不平衡的问题

yipeiwu_com5年前Python基础

当训练样本不均匀时,我们可以采用过采样、欠采样、数据增强等手段来避免过拟合。今天遇到一个3d点云数据集合,样本分布极不均匀,正例与负例相差4-5个数量级。数据增强效果就不会太好了,另外过采样也不太合适,因为是空间数据,新增的点有可能会对真实分布产生未知影响。所以采用欠采样来缓解类别不平衡的问题。

下面的代码展示了如何使用WeightedRandomSampler来完成抽样。

numDataPoints = 1000
data_dim = 5
bs = 100

# Create dummy data with class imbalance 9 to 1
data = torch.FloatTensor(numDataPoints, data_dim)
target = np.hstack((np.zeros(int(numDataPoints * 0.9), dtype=np.int32),
     np.ones(int(numDataPoints * 0.1), dtype=np.int32)))

print 'target train 0/1: {}/{}'.format(
 len(np.where(target == 0)[0]), len(np.where(target == 1)[0]))

class_sample_count = np.array(
 [len(np.where(target == t)[0]) for t in np.unique(target)])
weight = 1. / class_sample_count
samples_weight = np.array([weight[t] for t in target])

samples_weight = torch.from_numpy(samples_weight)
samples_weight = samples_weight.double()
sampler = WeightedRandomSampler(samples_weight, len(samples_weight))

target = torch.from_numpy(target).long()
train_dataset = torch.utils.data.TensorDataset(data, target)

train_loader = DataLoader(
 train_dataset, batch_size=bs, num_workers=1, sampler=sampler)

for i, (data, target) in enumerate(train_loader):
 print "batch index {}, 0/1: {}/{}".format(
  i,
  len(np.where(target.numpy() == 0)[0]),
  len(np.where(target.numpy() == 1)[0]))

核心部分为实际使用时替换下变量把sampler传递给DataLoader即可,注意使用了sampler就不能使用shuffle,另外需要指定采样点个数:

class_sample_count = np.array(
 [len(np.where(target == t)[0]) for t in np.unique(target)])
weight = 1. / class_sample_count
samples_weight = np.array([weight[t] for t in target])

samples_weight = torch.from_numpy(samples_weight)
samples_weight = samples_weight.double()
sampler = WeightedRandomSampler(samples_weight, len(samples_weight))

参考:https://discuss.pytorch.org/t/how-to-handle-imbalanced-classes/11264/2

以上这篇关于pytorch处理类别不平衡的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

利用TensorFlow训练简单的二分类神经网络模型的方法

利用TensorFlow训练简单的二分类神经网络模型的方法

利用TensorFlow实现《神经网络与机器学习》一书中4.7模式分类练习 具体问题是将如下图所示双月牙数据集分类。 使用到的工具: python3.5  &nbs...

Python实现打印螺旋矩阵功能的方法

Python实现打印螺旋矩阵功能的方法

本文实例讲述了Python实现打印螺旋矩阵功能的方法。分享给大家供大家参考,具体如下: 一、问题描述 输入N, 打印 N*N 螺旋矩阵 比如 N = 3,打印: 1 2 3 8 9...

python日期时间转为字符串或者格式化输出的实例

如下所示: 年月日时分秒 >>> print datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 2017-...

python 实时遍历日志文件

open 遍历一个大日志文件 使用 readlines() 还是 readline() ? 总体上 readlines() 不慢于python 一次次调用 readline(...

python 实现提取log文件中的关键句子,并进行统计分析

利用python开发了一个提取sim.log 中的各个关键步骤中的时间并进行统计的程序: #!/usr/bin/python2.6 import re,datetime file_n...