PyTorch加載自己的數(shù)據(jù)集實例詳解
數(shù)據(jù)預處理在解決深度學習問題的過程中,往往需要花費大量的時間和精力。 數(shù)據(jù)處理的質(zhì)量對訓練神經(jīng)網(wǎng)絡來說十分重要,良好的數(shù)據(jù)處理不僅會加速模型訓練, 更會提高模型性能。為解決這一問題,PyTorch提供了幾個高效便捷的工具, 以便使用者進行數(shù)據(jù)處理或增強等操作,同時可通過并行化加速數(shù)據(jù)加載。
數(shù)據(jù)集存放大致有以下兩種方式:
(1)所有數(shù)據(jù)集放在一個目錄下,文件名上附有標簽名,數(shù)據(jù)集存放格式如下: root/cat_dog/cat.01.jpg
root/cat_dog/cat.02.jpg
........................
root/cat_dog/dog.01.jpg
root/cat_dog/dog.02.jpg
......................
(2)不同類別的數(shù)據(jù)集放在不同目錄下,目錄名就是標簽,數(shù)據(jù)集存放格式如下:
root/ants/xxx.png
root/ants/xxy.jpeg
root/ants/xxz.png
................
root/bees/123.jpg
root/bees/nsdf3.png
root/bees/asd932_.png
..................
1.1 對第1種數(shù)據(jù)集的處理步驟
(1)生成包含各文件名的列表(List)
(2)定義Dataset的一個子類,該子類需要繼承Dataset類,查看Dataset類的源碼
(3)重寫父類Dataset中的兩個魔法方法: 一個是: __lent__(self),其功能是len(Dataset),返回Dataset的樣本數(shù)。 另一個是__getitem__(self,index),其功能假設索引為i,使Dataset[i]返回第i個樣本。
(4)使用torch.utils.data.DataLoader加載數(shù)據(jù)集Dataset.
1.2 實例詳解
以下以cat-dog數(shù)據(jù)集為例,說明如何實現(xiàn)自定義數(shù)據(jù)集的加載。
1.2.1 數(shù)據(jù)集結(jié)構(gòu)
所有數(shù)據(jù)集在cat-dog目錄下:
.\cat_dog\cat.01.jpg
.\cat_dog\cat.02.jpg
.\cat_dog\cat.03.jpg
....................
.\cat_dog\dog.01.jpg
.\cat_dog\dog.02.jpg
....................
1.2.2 導入需要用到的模塊
from torch.utils.data import DataLoader,Dataset from skimage import io,transform import matplotlib.pyplot as plt import oimport torch from torchvision import transforms, utils from PIL import Image import pandas as pd import numpy as np #過濾警告信息 import warnings warnings.filterwarnings("ignore")
1.2.3定義加載自定義數(shù)據(jù)的類
class MyDataset(Dataset): #繼承Dataset def __init__(self, path_dir, transform=None): #初始化一些屬性 self.path_dir = path_dir #文件路徑,如'.\data\cat-dog' self.transform = transform #對圖形進行處理,如標準化、截取、轉(zhuǎn)換等 self.images = os.listdir(self.path_dir)#把路徑下的所有文件放在一個列表中 def __len__(self):#返回整個數(shù)據(jù)集的大小 return len(self.images) def __getitem__(self,index):#根據(jù)索引index返回圖像及標簽 image_index = self.images[index]#根據(jù)索引獲取圖像文件名稱 img_path = os.path.join(self.path_dir, image_index)#獲取圖像的路徑或目錄 img = Image.open(img_path).convert('RGB')# 讀取圖像 # 根據(jù)目錄名稱獲取圖像標簽(cat或dog) label = img_path.split('\\')[-1].split('.')[0] #把字符轉(zhuǎn)換為數(shù)字cat-0,dog-1 label = 1 if 'dog' in label else 0 if self.transform is not None: img = self.transform(img) return img,label
1.2.4 實例化類
dataset = MyDataset('.\data\cat-dog',transform=None) img, label = dataset[0] #將啟動魔法方法__getitem__(0) print(type(img)) <class 'PIL.Image.Image'>
1.2.5 查看圖像形狀
i=1
for img, label in dataset:
if i
img的形狀(500, 374),label的值0
img的形狀(300, 280),label的值0
img的形狀(489, 499),label的值0
img的形狀(431, 410),label的值0
img的形狀(300, 224),label的值0
從上面返回樣本的形狀來看:
(1)每張圖片的大小不一樣,如果需要取batch訓練的神經(jīng)網(wǎng)絡來說很不友好。
(2)返回樣本的數(shù)值較大,未歸一化至[-1, 1]
為此需要對img進行轉(zhuǎn)換,如何轉(zhuǎn)換?只要使用torchvision中的transforms即可
1.2.6 對圖像數(shù)據(jù)進行處理
這里使用torchvision中的transforms模塊
from torchvision import transforms as T transform = T.Compose([ T.Resize(224), # 縮放圖片(Image),保持長寬比不變,最短邊為224像素 T.CenterCrop(224), # 從圖片中間切出224*224的圖片 T.ToTensor(), # 將圖片(Image)轉(zhuǎn)成Tensor,歸一化至[0, 1] T.Normalize(mean=[.5, .5, .5], std=[.5, .5, .5]) # 標準化至[-1, 1],規(guī)定均值和標準差 ])
1.2.7查看處理后的數(shù)據(jù)
dataset = MyDataset('.\data\cat-dog',transform=transform) for img, label in dataset: print("圖像img的形狀{},標簽label的值{}".format(img.shape, label)) print("圖像數(shù)據(jù)預處理后:\n",img) break
圖像img的形狀torch.Size([3, 224, 224]),標簽label的值0
圖像數(shù)據(jù)預處理后:
tensor([[[ 0.9059, 0.9137, 0.9137, ..., 0.9451, 0.9451, 0.9451],
[ 0.9059, 0.9137, 0.9137, ..., 0.9451, 0.9451, 0.9451],
[ 0.9059, 0.9137, 0.9137, ..., 0.9529, 0.9529, 0.9529],
...,
[-0.4824, -0.5294, -0.5373, ..., -0.9216, -0.9294, -0.9451],
[-0.4980, -0.5529, -0.5608, ..., -0.9294, -0.9373, -0.9529],
[-0.4980, -0.5529, -0.5686, ..., -0.9529, -0.9608, -0.9608]],
[[ 0.5686, 0.5765, 0.5765, ..., 0.7961, 0.7882, 0.7882],
[ 0.5686, 0.5765, 0.5765, ..., 0.7961, 0.7882, 0.7882],
[ 0.5686, 0.5765, 0.5765, ..., 0.8039, 0.7961, 0.7961],
...,
[-0.6078, -0.6471, -0.6549, ..., -0.9137, -0.9216, -0.9373],
[-0.6157, -0.6706, -0.6784, ..., -0.9216, -0.9294, -0.9451],
[-0.6157, -0.6706, -0.6863, ..., -0.9451, -0.9529, -0.9529]],
[[-0.0510, -0.0431, -0.0431, ..., 0.2078, 0.2157, 0.2157],
[-0.0510, -0.0431, -0.0431, ..., 0.2078, 0.2157, 0.2157],
[-0.0510, -0.0431, -0.0431, ..., 0.2157, 0.2235, 0.2235],
...,
[-0.9529, -0.9843, -0.9922, ..., -0.9529, -0.9608, -0.9765],
[-0.9686, -0.9922, -1.0000, ..., -0.9608, -0.9686, -0.9843],
[-0.9686, -0.9922, -1.0000, ..., -0.9843, -0.9922, -0.9922]]])
由此可知,數(shù)據(jù)已標準化、規(guī)范化。
1.2.8對數(shù)據(jù)集進行批量加載
使用DataLoader模塊,對數(shù)據(jù)集dataset進行批量加載
#使用DataLoader加載數(shù)據(jù) dataloader = DataLoader(dataset,batch_size=4,shuffle=True) for batch_datas, batch_labels in dataloader: print(batch_datas.size(),batch_labels.size()) torch.Size([4, 3, 224, 224]) torch.Size([4]) torch.Size([4, 3, 224, 224]) torch.Size([4]) torch.Size([4, 3, 224, 224]) torch.Size([4]) torch.Size([4, 3, 224, 224]) torch.Size([4]) torch.Size([4, 3, 224, 224]) torch.Size([4]) torch.Size([4, 3, 224, 224]) torch.Size([4]) torch.Size([4, 3, 224, 224]) torch.Size([4]) torch.Size([4, 3, 224, 224]) torch.Size([4]) torch.Size([4, 3, 224, 224]) torch.Size([4]) torch.Size([4, 3, 224, 224]) torch.Size([4]) torch.Size([2, 3, 224, 224]) torch.Size([2])
1.2.9隨機查看一個批次的圖像
import torchvision import matplotlib.pyplot as plt import numpy as np %matplotlib inline # 顯示圖像 def imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.show() # 隨機獲取部分訓練數(shù)據(jù) dataiter = iter(dataloader) images, labels = dataiter.next() # 顯示圖像 imshow(torchvision.utils.make_grid(images)) # 打印標簽 print(' '.join('%s' % ["小狗" if labels[j].item()==1 else "小貓" for j in range(4)]))
2 對第2種數(shù)據(jù)集的處理
處理這種情況比較簡單,可分為2步:
(1)使用datasets.ImageFolder讀取、處理圖像。
(2)使用.data.DataLoader批量加載數(shù)據(jù)集,示例如下:
import torch from torchvision import transforms, datasets data_transform = transforms.Compose([ transforms.RandomSizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) hymenoptera_dataset = datasets.ImageFolder(root='.\catdog\train', transform=data_transform) dataset_loader = torch.utils.data.DataLoader(hymenoptera_dataset,
總結(jié)
到此這篇關(guān)于PyTorch加載自己的數(shù)據(jù)集實例詳解的文章就介紹到這了,更多相關(guān)PyTorch加載 數(shù)據(jù)集內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
對python numpy.array插入一行或一列的方法詳解
今天小編就為大家分享一篇對python numpy.array插入一行或一列的方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01python 通過可變參數(shù)計算n個數(shù)的乘積方法
今天小編就為大家分享一篇python 通過可變參數(shù)計算n個數(shù)的乘積方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python Pytest裝飾器@pytest.mark.parametrize詳解
本文主要介紹了Python Pytest裝飾器@pytest.mark.parametrize詳解,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08結(jié)合Python網(wǎng)絡爬蟲做一個今日新聞小程序
本篇文章介紹了我在開發(fā)過程中遇到的一個問題,以及解決該問題的過程及思路,通讀本篇對大家的學習或工作具有一定的價值,需要的朋友可以參考下2021-09-09