小编给大家分享一下pytorch如何处理类别不平衡的问题,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
下面的代码展示了如何使用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))
以上是“pytorch如何处理类别不平衡的问题”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。