torch.utils.data.DataLoader與迭代器轉(zhuǎn)換操作
在做實(shí)驗(yàn)時(shí),我們常常會使用用開源的數(shù)據(jù)集進(jìn)行測試。而Pytorch中內(nèi)置了許多數(shù)據(jù)集,這些數(shù)據(jù)集我們常常使用DataLoader類進(jìn)行加載。
如下面這個(gè)我們使用DataLoader類加載torch.vision中的FashionMNIST數(shù)據(jù)集。
from torch.utils.data import DataLoader from torchvision import datasets from torchvision.transforms import ToTensor import matplotlib.pyplot as plt training_data = datasets.FashionMNIST( ? ? root="data", ? ? train=True, ? ? download=True, ? ? transform=ToTensor() ) test_data = datasets.FashionMNIST( ? ? root="data", ? ? train=False, ? ? download=True, ? ? transform=ToTensor() )
我們接下來定義Dataloader對象用于加載這兩個(gè)數(shù)據(jù)集:
train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True) test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)
那么這個(gè)train_dataloader究竟是什么類型呢?
print(type(train_dataloader)) ?# <class 'torch.utils.data.dataloader.DataLoader'>
我們可以將先其轉(zhuǎn)換為迭代器類型。
print(type(iter(train_dataloader)))# <class 'torch.utils.data.dataloader._SingleProcessDataLoaderIter'>
然后再使用next(iter(train_dataloader))從迭代器里取數(shù)據(jù),如下所示:
train_features, train_labels = next(iter(train_dataloader))
print(f"Feature batch shape: {train_features.size()}")
print(f"Labels batch shape: {train_labels.size()}")
img = train_features[0].squeeze()
label = train_labels[0]
plt.imshow(img, cmap="gray")
plt.show()
print(f"Label: {label}")可以看到我們成功獲取了數(shù)據(jù)集中第一張圖片的信息,控制臺打?。?/strong>
Feature batch shape: torch.Size([64, 1, 28, 28]) Labels batch shape: torch.Size([64]) Label: 2
圖片可視化顯示如下:

不過有讀者可能就會產(chǎn)生疑問,很多時(shí)候我們并沒有將DataLoader類型強(qiáng)制轉(zhuǎn)換成迭代器類型呀,大多數(shù)時(shí)候我們會寫如下代碼:
for train_features, train_labels in train_dataloader:?
? ? print(train_features.shape) # torch.Size([64, 1, 28, 28])
? ? print(train_features[0].shape) # torch.Size([1, 28, 28])
? ? print(train_features[0].squeeze().shape) # torch.Size([28, 28])
? ??
? ? img = train_features[0].squeeze()
? ? label = train_labels[0]
? ? plt.imshow(img, cmap="gray")
? ? plt.show()
? ? print(f"Label: {label}")可以看到,該代碼也能夠正常迭代訓(xùn)練數(shù)據(jù),前三個(gè)樣本的控制臺打印輸出為:
torch.Size([64, 1, 28, 28]) torch.Size([1, 28, 28]) torch.Size([28, 28]) Label: 7 torch.Size([64, 1, 28, 28]) torch.Size([1, 28, 28]) torch.Size([28, 28]) Label: 4 torch.Size([64, 1, 28, 28]) torch.Size([1, 28, 28]) torch.Size([28, 28]) Label: 1
那么為什么我們這里沒有顯式將Dataloader轉(zhuǎn)換為迭代器類型呢,其實(shí)是Python語言for循環(huán)的一種機(jī)制,一旦我們用for ... in ...句式來迭代一個(gè)對象,那么Python解釋器就會偷偷地自動(dòng)幫我們創(chuàng)建好迭代器,也就是說
for train_features, train_labels in train_dataloader:
實(shí)際上等同于
for train_features, train_labels in iter(train_dataloader):
更進(jìn)一步,這實(shí)際上等同于
train_iterator = iter(train_dataloader) try: ? ? while True: ? ? ? ? train_features, train_labels = next(train_iterator) except StopIteration: ? ? pass
推而廣之,我們在用Python迭代直接迭代列表時(shí):
for x in [1, 2, 3, 4]:
其實(shí)Python解釋器已經(jīng)為我們隱式轉(zhuǎn)換為迭代器了:
list_iterator = iter([1, 2, 3, 4]) try: ? ? while True: ? ? ? ? x = next(list_iterator) except StopIteration: ? ? pass
到此這篇關(guān)于torch.utils.data.DataLoader與迭代器轉(zhuǎn)換操作的文章就介紹到這了,更多相關(guān)torch.utils.data.DataLoader與迭代器轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用Python代碼實(shí)現(xiàn)一鍵摳背景功能
這篇文章主要給大家介紹了關(guān)于如何利用Python代碼實(shí)現(xiàn)一鍵摳背景的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Python閉包的兩個(gè)注意事項(xiàng)(推薦)
閉包就是根據(jù)不同的配置信息得到不同的結(jié)果。下面通過本文給大家分享Python閉包的兩個(gè)注意事項(xiàng),需要的朋友參考下2017-03-03
python計(jì)算最大優(yōu)先級隊(duì)列實(shí)例
python計(jì)算最大優(yōu)先級隊(duì)列實(shí)例,大家參考使用吧2013-12-12
Pytorch?PyG實(shí)現(xiàn)EdgePool圖分類
這篇文章主要為大家介紹了Pytorch?PyG實(shí)現(xiàn)EdgePool圖分類示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
Python切換pip源兩種方法(解決pip?install慢)
這篇文章主要給大家介紹了關(guān)于Python切換pip源兩種方法(解決pip?install慢),我總結(jié)的這幾種更換pip源的常用方式,希望可以幫助您成功配置國內(nèi)源,解決安裝Python包速度慢的問題,需要的朋友可以參考下2023-11-11

