Pytorch數(shù)據(jù)讀取之Dataset和DataLoader知識總結(jié)
一、
確保安裝
- scikit-image
- numpy
二、Dataset
一個例子:
# 導入需要的包
import torch
import torch.utils.data.dataset as Dataset
import numpy as np
# 編造數(shù)據(jù)
Data = np.asarray([[1, 2], [3, 4],[5, 6], [7, 8]])
Label = np.asarray([[0], [1], [0], [2]])
# 數(shù)據(jù)[1,2],對應的標簽是[0],數(shù)據(jù)[3,4],對應的標簽是[1]
#創(chuàng)建子類
class subDataset(Dataset.Dataset):
#初始化,定義數(shù)據(jù)內(nèi)容和標簽
def __init__(self, Data, Label):
self.Data = Data
self.Label = Label
#返回數(shù)據(jù)集大小
def __len__(self):
return len(self.Data)
#得到數(shù)據(jù)內(nèi)容和標簽
def __getitem__(self, index):
data = torch.Tensor(self.Data[index])
label = torch.IntTensor(self.Label[index])
return data, label
# 主函數(shù)
if __name__ == '__main__':
dataset = subDataset(Data, Label)
print(dataset)
print('dataset大小為:', dataset.__len__())
print(dataset.__getitem__(0))
print(dataset[0])
輸出的結(jié)果

我們有了對Dataset的一個整體的把握,再來分析里面的細節(jié):
#創(chuàng)建子類 class subDataset(Dataset.Dataset):
創(chuàng)建子類時,繼承的時Dataset.Dataset,不是一個Dataset。因為Dataset是module模塊,不是class類,所以需要調(diào)用module里的class才行,因此是Dataset.Dataset!
len和getitem這兩個函數(shù),前者給出數(shù)據(jù)集的大小**,后者是用于查找數(shù)據(jù)和標簽。是最重要的兩個函數(shù),我們后續(xù)如果要對數(shù)據(jù)做一些操作基本上都是再這兩個函數(shù)的基礎(chǔ)上進行。
三、DatasetLoader
DataLoader(dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_works=0, clollate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, multiprocessing_context=None)
功能:構(gòu)建可迭代的數(shù)據(jù)裝載器;
dataset:Dataset類,決定數(shù)據(jù)從哪里讀取及如何讀取;數(shù)據(jù)集的路徑
batchsize:批大??;
num_works:是否多進程讀取數(shù)據(jù);只對于CPU
shuffle:每個epoch是否打亂;
drop_last:當樣本數(shù)不能被batchsize整除時,是否舍棄最后一批數(shù)據(jù);
Epoch:所有訓練樣本都已輸入到模型中,稱為一個Epoch;
Iteration:一批樣本輸入到模型中,稱之為一個Iteration;
Batchsize:批大小,決定一個Epoch中有多少個Iteration;
還是舉一個實例:
import torch
import torch.utils.data.dataset as Dataset
import torch.utils.data.dataloader as DataLoader
import numpy as np
Data = np.asarray([[1, 2], [3, 4],[5, 6], [7, 8]])
Label = np.asarray([[0], [1], [0], [2]])
#創(chuàng)建子類
class subDataset(Dataset.Dataset):
#初始化,定義數(shù)據(jù)內(nèi)容和標簽
def __init__(self, Data, Label):
self.Data = Data
self.Label = Label
#返回數(shù)據(jù)集大小
def __len__(self):
return len(self.Data)
#得到數(shù)據(jù)內(nèi)容和標簽
def __getitem__(self, index):
data = torch.Tensor(self.Data[index])
label = torch.IntTensor(self.Label[index])
return data, label
if __name__ == '__main__':
dataset = subDataset(Data, Label)
print(dataset)
print('dataset大小為:', dataset.__len__())
print(dataset.__getitem__(0))
print(dataset[0])
#創(chuàng)建DataLoader迭代器,相當于我們要先定義好前面說的Dataset,然后再用Dataloader來對數(shù)據(jù)進行一些操作,比如是否需要打亂,則shuffle=True,是否需要多個進程讀取數(shù)據(jù)num_workers=4,就是四個進程
dataloader = DataLoader.DataLoader(dataset,batch_size= 2, shuffle = False, num_workers= 4)
for i, item in enumerate(dataloader): #可以用enumerate來提取出里面的數(shù)據(jù)
print('i:', i)
data, label = item #數(shù)據(jù)是一個元組
print('data:', data)
print('label:', label)
四、將Dataset數(shù)據(jù)和標簽放在GPU上(代碼執(zhí)行順序出錯則會有bug)
這部分可以直接去看博客:Dataset和DataLoader
總結(jié)下來時有兩種方法解決
1.如果在創(chuàng)建Dataset的類時,定義__getitem__方法的時候,將數(shù)據(jù)轉(zhuǎn)變?yōu)镚PU類型。則需要將Dataloader里面的參數(shù)num_workers設置為0,因為這個參數(shù)是對于CPU而言的。如果數(shù)據(jù)改成了GPU,則只能單進程。如果是在Dataloader的部分,先多個子進程讀取,再轉(zhuǎn)變?yōu)镚PU,則num_wokers不用修改。就是上述__getitem__部分的代碼,移到Dataloader部分。
2.不過一般來講,數(shù)據(jù)集和標簽不會像我們上述編輯的那么簡單。一般再kaggle上的標簽都是存在CSV這種文件中。需要pandas的配合。
這個進階可以看:WRITING CUSTOM DATASETS, DATALOADERS AND TRANSFORMS,他是用人臉圖片作為數(shù)據(jù)和人臉特征點作為標簽。
到此這篇關(guān)于Pytorch數(shù)據(jù)讀取之Dataset和DataLoader知識總結(jié)的文章就介紹到這了,更多相關(guān)詳解Dataset和DataLoader內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信