關(guān)于pytorch處理類別不平衡的問題
當(dāng)訓(xùn)練樣本不均勻時,我們可以采用過采樣、欠采樣、數(shù)據(jù)增強等手段來避免過擬合。今天遇到一個3d點云數(shù)據(jù)集合,樣本分布極不均勻,正例與負例相差4-5個數(shù)量級。數(shù)據(jù)增強效果就不會太好了,另外過采樣也不太合適,因為是空間數(shù)據(jù),新增的點有可能會對真實分布產(chǎn)生未知影響。所以采用欠采樣來緩解類別不平衡的問題。
下面的代碼展示了如何使用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,另外需要指定采樣點個數(shù):
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
以上這篇關(guān)于pytorch處理類別不平衡的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python 實現(xiàn)將txt文件多行合并為一行并將中間的空格去掉方法
今天小編就為大家分享一篇python 實現(xiàn)將txt文件多行合并為一行并將中間的空格去掉方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12python tkinterEntry組件設(shè)置默認值方式
使用Tkinter庫中的Entry組件創(chuàng)建文本輸入框時,可以通過insert方法在指定位置插入默認文本作為提示,結(jié)合使用focus和focusin事件,可以實現(xiàn)用戶點擊時清除默認文本,以便輸入自定義內(nèi)容2024-09-09Python內(nèi)置的HTTP協(xié)議服務(wù)器SimpleHTTPServer使用指南
這篇文章主要介紹了Python內(nèi)置的HTTP協(xié)議服務(wù)器SimpleHTTPServer使用指南,SimpleHTTPServer本身的功能十分簡單,文中介紹了需要的朋友可以參考下2016-03-03Python 實例方法、類方法、靜態(tài)方法的區(qū)別與作用
Python中至少有三種比較常見的方法類型,即實例方法,類方法、靜態(tài)方法。它們是如何定義的呢?如何調(diào)用的呢?它們又有何區(qū)別和作用呢?感興趣的朋友跟隨小編一起看看吧2019-08-08