python機(jī)器學(xué)習(xí)pytorch自定義數(shù)據(jù)加載器
正文
處理數(shù)據(jù)樣本的代碼可能會(huì)逐漸變得混亂且難以維護(hù);理想情況下,我們希望我們的數(shù)據(jù)集代碼與我們的模型訓(xùn)練代碼分離,以獲得更好的可讀性和模塊化。PyTorch 提供了兩個(gè)數(shù)據(jù)原語(yǔ):torch.utils.data.DataLoader和torch.utils.data.Dataset 允許我們使用預(yù)加載的數(shù)據(jù)集以及自定義數(shù)據(jù)。 Dataset存儲(chǔ)樣本及其對(duì)應(yīng)的標(biāo)簽,DataLoader封裝了一個(gè)迭代器用于遍歷Dataset,以便輕松訪問(wèn)樣本數(shù)據(jù)。
PyTorch 領(lǐng)域庫(kù)提供了許多預(yù)加載的數(shù)據(jù)集(例如 FashionMNIST),這些數(shù)據(jù)集繼承自torch.utils.data.Dataset并實(shí)現(xiàn)了特定于特定數(shù)據(jù)的功能。它們可用于對(duì)您的模型進(jìn)行原型設(shè)計(jì)和基準(zhǔn)測(cè)試。你可以在這里找到它們:圖像數(shù)據(jù)集、 文本數(shù)據(jù)集和 音頻數(shù)據(jù)集
1. 加載數(shù)據(jù)集
下面是如何從 TorchVision 加載Fashion-MNIST數(shù)據(jù)集的示例。Fashion-MNIST 是 Zalando 文章圖像的數(shù)據(jù)集,由 60,000 個(gè)訓(xùn)練示例和 10,000 個(gè)測(cè)試示例組成。每個(gè)示例都包含 28×28 灰度圖像和來(lái)自 10 個(gè)類別之一的相關(guān)標(biāo)簽。
我們使用以下參數(shù)加載FashionMNIST 數(shù)據(jù)集:
root是存儲(chǔ)訓(xùn)練/測(cè)試數(shù)據(jù)的路徑,train指定訓(xùn)練或測(cè)試數(shù)據(jù)集,download=True如果數(shù)據(jù)不可用,則從 Internet 下載數(shù)據(jù)root。transform并target_transform指定特征和標(biāo)簽轉(zhuǎn)換
import torch
from torch.utils.data import Dataset
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()
)
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to data/FashionMNIST/raw/train-images-idx3-ubyte.gz 0%| | 0/26421880 [00:00<?, ?it/s] 0%| | 32768/26421880 [00:00<01:26, 303914.51it/s] 0%| | 65536/26421880 [00:00<01:27, 301769.74it/s] 0%| | 131072/26421880 [00:00<01:00, 437795.76it/s] 1%| | 229376/26421880 [00:00<00:42, 621347.43it/s] 2%|1 | 491520/26421880 [00:00<00:20, 1259673.64it/s] 4%|3 | 950272/26421880 [00:00<00:11, 2264911.11it/s] 7%|7 | 1933312/26421880 [00:00<00:05, 4467299.81it/s] 15%|#4 | 3833856/26421880 [00:00<00:02, 8587616.55it/s] 26%|##6 | 6881280/26421880 [00:00<00:01, 14633777.99it/s] 37%|###7 | 9830400/26421880 [00:01<00:00, 18150145.01it/s] 49%|####8 | 12910592/26421880 [00:01<00:00, 21161097.17it/s] 61%|###### | 16023552/26421880 [00:01<00:00, 23366004.89it/s] 72%|#######2 | 19136512/26421880 [00:01<00:00, 24967488.10it/s] 84%|########4 | 22249472/26421880 [00:01<00:00, 26016258.24it/s] 95%|#########5| 25231360/26421880 [00:01<00:00, 26218488.24it/s] 100%|##########| 26421880/26421880 [00:01<00:00, 15984902.80it/s] Extracting data/FashionMNIST/raw/train-images-idx3-ubyte.gz to data/FashionMNIST/raw Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw/train-labels-idx1-ubyte.gz 0%| | 0/29515 [00:00<?, ?it/s] 100%|##########| 29515/29515 [00:00<00:00, 268356.24it/s] 100%|##########| 29515/29515 [00:00<00:00, 266767.69it/s] Extracting data/FashionMNIST/raw/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz 0%| | 0/4422102 [00:00<?, ?it/s] 1%| | 32768/4422102 [00:00<00:14, 302027.13it/s] 1%|1 | 65536/4422102 [00:00<00:14, 300501.69it/s] 3%|2 | 131072/4422102 [00:00<00:09, 436941.45it/s] 5%|5 | 229376/4422102 [00:00<00:06, 619517.19it/s] 10%|9 | 425984/4422102 [00:00<00:03, 1044158.55it/s] 20%|## | 884736/4422102 [00:00<00:01, 2114396.73it/s] 40%|#### | 1769472/4422102 [00:00<00:00, 4067080.68it/s] 80%|######## | 3538944/4422102 [00:00<00:00, 7919346.09it/s] 100%|##########| 4422102/4422102 [00:00<00:00, 5036535.17it/s] Extracting data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz 0%| | 0/5148 [00:00<?, ?it/s] 100%|##########| 5148/5148 [00:00<00:00, 22168662.21it/s] Extracting data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw
2. 迭代和可視化數(shù)據(jù)集
我們可以像python 列表一樣索引Datasets,比如:
training_data[index].
我們用matplotlib來(lái)可視化訓(xùn)練數(shù)據(jù)中的一些樣本。
labels_map = {
0: "T-Shirt",
1: "Trouser",
2: "Pullover",
3: "Dress",
4: "Coat",
5: "Sandal",
6: "Shirt",
7: "Sneaker",
8: "Bag",
9: "Ankle Boot",
}
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
sample_idx = torch.randint(len(training_data), size=(1,)).item()
img, label = training_data[sample_idx]
figure.add_subplot(rows, cols, i)
plt.title(labels_map[label])
plt.axis("off")
plt.imshow(img.squeeze(), cmap="gray")
plt.show()

3.創(chuàng)建自定義數(shù)據(jù)集
自定義 Dataset 類必須實(shí)現(xiàn)三個(gè)函數(shù):init、len__和__getitem。
比如: FashionMNIST 圖像存儲(chǔ)在一個(gè)目錄img_dir中,它們的標(biāo)簽分別存儲(chǔ)在一個(gè) CSV 文件annotations_file中。
在接下來(lái)的部分中,我們將分析每個(gè)函數(shù)中發(fā)生的事情。
import os
import pandas as pd
from torchvision.io import read_image
class CustomImageDataset(Dataset):
def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
self.img_labels = pd.read_csv(annotations_file)
self.img_dir = img_dir
self.transform = transform
self.target_transform = target_transform
def __len__(self):
return len(self.img_labels)
def __getitem__(self, idx):
img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])
image = read_image(img_path)
label = self.img_labels.iloc[idx, 1]
if self.transform:
image = self.transform(image)
if self.target_transform:
label = self.target_transform(label)
return image, label
3.1 __init__
init 函數(shù)在實(shí)例化 Dataset 對(duì)象時(shí)運(yùn)行一次。我們初始化包含圖像、注釋文件和兩種轉(zhuǎn)換的目錄(在下一節(jié)中更詳細(xì)地介紹)。
labels.csv 文件如下所示:
tshirt1.jpg, 0 tshirt2.jpg, 0 ...... ankleboot999.jpg, 9
def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
self.img_labels = pd.read_csv(annotations_file)
self.img_dir = img_dir
self.transform = transform
self.target_transform = target_transform
3.2 __len__
len 函數(shù)返回我們數(shù)據(jù)集中的樣本數(shù)。
例子:
def __len__(self):
return len(self.img_labels)
3.3 __getitem__
getitem 函數(shù)從給定索引處的數(shù)據(jù)集中加載并返回一個(gè)樣本idx?;谒饕?,它識(shí)別圖像在磁盤(pán)上的位置,使用 將其轉(zhuǎn)換為張量read_image,從 csv 數(shù)據(jù)中檢索相應(yīng)的標(biāo)簽self.img_labels,調(diào)用它們的轉(zhuǎn)換函數(shù)(如果適用),并返回張量圖像和相應(yīng)的標(biāo)簽一個(gè)元組。
def __getitem__(self, idx):
img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])
image = read_image(img_path)
label = self.img_labels.iloc[idx, 1]
if self.transform:
image = self.transform(image)
if self.target_transform:
label = self.target_transform(label)
return image, label
4. 使用 DataLoaders 為訓(xùn)練準(zhǔn)備數(shù)據(jù)
Dataset一次加載一個(gè)樣本數(shù)據(jù)和其對(duì)應(yīng)的label。在訓(xùn)練模型時(shí),我們通常希望以minibatches“小批量”的形式傳遞樣本,在每個(gè) epoch 重新洗牌以減少模型過(guò)擬合,并使用 Pythonmultiprocessing加速數(shù)據(jù)檢索。
DataLoader是一個(gè)可迭代對(duì)象,它封裝了復(fù)雜性并暴漏了簡(jiǎn)單的API。
from torch.utils.data import DataLoader train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True) test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)
5.遍歷 DataLoader
我們已將該數(shù)據(jù)集加載到 DataLoader中,并且可以根據(jù)需要遍歷數(shù)據(jù)集。下面的每次迭代都會(huì)返回一批train_features和train_labels(分別包含batch_size=64特征和標(biāo)簽)。因?yàn)槲覀冎付?code>shuffle=True了 ,所以在我們遍歷所有批次之后,數(shù)據(jù)被打亂(為了更細(xì)粒度地控制數(shù)據(jù)加載順序,請(qǐng)查看Samplers)。
# Display image and label.
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}")

Feature batch shape: torch.Size([64, 1, 28, 28]) Labels batch shape: torch.Size([64]) Label: 4
以上就是python機(jī)器學(xué)習(xí)pytorch自定義數(shù)據(jù)加載器的詳細(xì)內(nèi)容,更多關(guān)于python pytorch自定義數(shù)據(jù)加載器的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Python機(jī)器學(xué)習(xí)性能度量利用鳶尾花數(shù)據(jù)繪制P-R曲線
- Python機(jī)器學(xué)習(xí)利用鳶尾花數(shù)據(jù)繪制ROC和AUC曲線
- python機(jī)器學(xué)習(xí)pytorch?張量基礎(chǔ)教程
- python機(jī)器學(xué)習(xí)Logistic回歸原理推導(dǎo)
- python機(jī)器學(xué)習(xí)混淆矩陣及confusion?matrix函數(shù)使用
- python機(jī)器學(xué)習(xí)GCN圖卷積神經(jīng)網(wǎng)絡(luò)原理解析
- Python BentoML構(gòu)建部署和管理機(jī)器學(xué)習(xí)模型技巧掌握
相關(guān)文章
詳解Pandas與openpyxl庫(kù)的超強(qiáng)結(jié)合
Pandas絕對(duì)是Python中處理Excel最快、最好用的庫(kù),但是使用 openpyxl 的一些優(yōu)勢(shì)是能夠輕松地使用樣式、條件格式等自定義電子表格,感興趣的可以了解一下2021-09-09
Python調(diào)用GPT3.5接口的最新方法實(shí)例詳解
這篇文章主要介紹了Python調(diào)用GPT3.5接口的最新方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03
python hashlib加密實(shí)現(xiàn)代碼
這篇文章主要介紹了python hashlib加密實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
Pycharm中import torch報(bào)錯(cuò)的快速解決方法
這篇文章主要介紹了Pycharm中import torch報(bào)錯(cuò)的快速解決方法,很多朋友容易碰到這個(gè)問(wèn)題,今天小編特此把解決方案分享到腳本之家平臺(tái)供大家參考,需要的朋友可以參考下2020-03-03
Python中在腳本中引用其他文件函數(shù)的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇Python中在腳本中引用其他文件函數(shù)的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06
Python?Collections庫(kù)的高級(jí)功能使用示例詳解
Python的collections庫(kù)提供了一系列有用的數(shù)據(jù)類型,擴(kuò)展了內(nèi)建的數(shù)據(jù)類型,為開(kāi)發(fā)者提供了更多高級(jí)功能,本文將深入探討collections庫(kù)的一些高級(jí)功能,通過(guò)詳細(xì)的示例代碼演示,幫助大家更好地理解和應(yīng)用這些功能2023-12-12
Python Sql數(shù)據(jù)庫(kù)增刪改查操作簡(jiǎn)單封裝
這篇文章主要為大家介紹了Python Sql數(shù)據(jù)庫(kù)增刪改查操作簡(jiǎn)單封裝,感興趣的小伙伴們可以參考一下2016-04-04
python基于multiprocessing的多進(jìn)程創(chuàng)建方法
這篇文章主要介紹了python基于multiprocessing的多進(jìn)程創(chuàng)建方法,實(shí)例分析了multiprocessing模塊操作進(jìn)程的相關(guān)技巧,需要的朋友可以參考下2015-06-06

