关于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设计】。

相关文章

python 生成图形验证码的方法示例

python 生成图形验证码的方法示例

日常在网站使用过程中经常遇到图形验证,今天准备自己做个图形验证码,这算是个简单的功能,也适合新手练习的,便于自己学习。 主要用到的库--PIL图像处理库,简单的思路,我们需要随机的颜...

python中装饰器级连的使用方法示例

前言 最近在学习python,学会了为什么要使用装饰器,也明白了装饰器是什么了,但是你也许会问,是否可以在装饰器前面再添加一层装饰器,会怎么样呢?就像大楼一样,一层一层地叠在一起。其实是...

python操作摄像头截图实现远程监控的例子

最近用python写了一个远程监控的程序,主要功能有:1.用邮件控制所以功能2.可以对屏幕截图,屏幕截图发送到邮箱3.可以用摄像头获取图片,这些图片上传到七牛4.开机自启动 复制代码 代...

zbar解码二维码和条形码示例

复制代码 代码如下:#!/usr/bin/env python# coding: u8import osimport zbarimport Imageimport urllibimpor...

浅谈Python由__dict__和dir()引发的一些思考

关于__dict__和dir()的区别和作用请参考这篇文章: 基于Python __dict__与dir()的区别详解 说下我当时遇到的问题: class Demo: def _...