最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python機(jī)器學(xué)習(xí)pytorch自定義數(shù)據(jù)加載器

 更新時間:2022年10月12日 14:45:58   作者:0+xuejianxinokok  
這篇文章主要為大家介紹了python機(jī)器學(xué)習(xí)pytorch自定義數(shù)據(jù)加載器使用示例學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

正文

處理數(shù)據(jù)樣本的代碼可能會逐漸變得混亂且難以維護(hù);理想情況下,我們希望我們的數(shù)據(jù)集代碼與我們的模型訓(xùn)練代碼分離,以獲得更好的可讀性和模塊化。PyTorch 提供了兩個數(shù)據(jù)原語:torch.utils.data.DataLoadertorch.utils.data.Dataset 允許我們使用預(yù)加載的數(shù)據(jù)集以及自定義數(shù)據(jù)。 Dataset存儲樣本及其對應(yīng)的標(biāo)簽,DataLoader封裝了一個迭代器用于遍歷Dataset,以便輕松訪問樣本數(shù)據(jù)。

PyTorch 領(lǐng)域庫提供了許多預(yù)加載的數(shù)據(jù)集(例如 FashionMNIST),這些數(shù)據(jù)集繼承自torch.utils.data.Dataset并實現(xiàn)了特定于特定數(shù)據(jù)的功能。它們可用于對您的模型進(jìn)行原型設(shè)計和基準(zhǔn)測試。你可以在這里找到它們:圖像數(shù)據(jù)集、 文本數(shù)據(jù)集和 音頻數(shù)據(jù)集

1. 加載數(shù)據(jù)集

下面是如何從 TorchVision 加載Fashion-MNIST數(shù)據(jù)集的示例。Fashion-MNIST 是 Zalando 文章圖像的數(shù)據(jù)集,由 60,000 個訓(xùn)練示例和 10,000 個測試示例組成。每個示例都包含 28×28 灰度圖像和來自 10 個類別之一的相關(guān)標(biāo)簽。

我們使用以下參數(shù)加載FashionMNIST 數(shù)據(jù)集:

  • root是存儲訓(xùn)練/測試數(shù)據(jù)的路徑,
  • train指定訓(xùn)練或測試數(shù)據(jù)集,
  • download=True如果數(shù)據(jù)不可用,則從 Internet 下載數(shù)據(jù)root。
  • transformtarget_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來可視化訓(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 類必須實現(xiàn)三個函數(shù):init、len__和__getitem

比如: FashionMNIST 圖像存儲在一個目錄img_dir中,它們的標(biāo)簽分別存儲在一個 CSV 文件annotations_file中。

在接下來的部分中,我們將分析每個函數(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ù)在實例化 Dataset 對象時運行一次。我們初始化包含圖像、注釋文件和兩種轉(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ù)集中加載并返回一個樣本idx?;谒饕R別圖像在磁盤上的位置,使用 將其轉(zhuǎn)換為張量read_image,從 csv 數(shù)據(jù)中檢索相應(yīng)的標(biāo)簽self.img_labels,調(diào)用它們的轉(zhuǎn)換函數(shù)(如果適用),并返回張量圖像和相應(yīng)的標(biāo)簽一個元組。

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一次加載一個樣本數(shù)據(jù)和其對應(yīng)的label。在訓(xùn)練模型時,我們通常希望以minibatches“小批量”的形式傳遞樣本,在每個 epoch 重新洗牌以減少模型過擬合,并使用 Pythonmultiprocessing加速數(shù)據(jù)檢索。

DataLoader是一個可迭代對象,它封裝了復(fù)雜性并暴漏了簡單的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ù)集。下面的每次迭代都會返回一批train_featurestrain_labels(分別包含batch_size=64特征和標(biāo)簽)。因為我們指定shuffle=True了 ,所以在我們遍歷所有批次之后,數(shù)據(jù)被打亂(為了更細(xì)粒度地控制數(shù)據(jù)加載順序,請查看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ù)加載器的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python實現(xiàn)為圖像添加下雪特效

    Python實現(xiàn)為圖像添加下雪特效

    這篇文章主要為大家介紹了通過Python為圖像添加下雪特效,文中的示例代碼講解詳細(xì),對學(xué)習(xí)Python有一定的幫助,感興趣的小伙伴可以了解一下
    2021-12-12
  • python?密碼驗證(滑塊驗證)

    python?密碼驗證(滑塊驗證)

    滑塊密碼在很多登錄界面都可以看到,本文主要介紹了python?密碼驗證(滑塊驗證),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • python爬取基于m3u8協(xié)議的ts文件并合并

    python爬取基于m3u8協(xié)議的ts文件并合并

    這篇文章主要為大家詳細(xì)介紹了python爬取基于m3u8協(xié)議的ts文件并合并,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-04-04
  • django-rest-swagger對API接口注釋的方法

    django-rest-swagger對API接口注釋的方法

    今天小編就為大家分享一篇django-rest-swagger對API接口注釋的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Python實戰(zhàn)之外星人入侵游戲示例代碼

    Python實戰(zhàn)之外星人入侵游戲示例代碼

    這篇文章主要介紹了利用Python編寫的外星人入侵游戲的示例代碼,文中的代碼講解詳細(xì),對我們學(xué)習(xí)Python有一定的幫助,感興趣的可以學(xué)習(xí)一下
    2022-01-01
  • python自動化測試之破解圖文驗證碼

    python自動化測試之破解圖文驗證碼

    這篇文章介紹了python自動化測試之破解圖文驗證碼的解決方案,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-07-07
  • python圖片水印加密的幾種處理小結(jié)

    python圖片水印加密的幾種處理小結(jié)

    本文主要介紹了python圖片水印加密的幾種處理小結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • 使用Python做定時任務(wù)及時了解互聯(lián)網(wǎng)動態(tài)

    使用Python做定時任務(wù)及時了解互聯(lián)網(wǎng)動態(tài)

    這篇文章主要介紹了使用Python做定時任務(wù)及時了解互聯(lián)網(wǎng)動態(tài),需要的朋友可以參考下
    2019-05-05
  • python簡單程序讀取串口信息的方法

    python簡單程序讀取串口信息的方法

    這篇文章主要介紹了python簡單程序讀取串口信息的方法,涉及Python操作serial模塊的技巧,需要的朋友可以參考下
    2015-03-03
  • python lambda函數(shù)及三個常用的高階函數(shù)

    python lambda函數(shù)及三個常用的高階函數(shù)

    這篇文章主要介紹了python lambda函數(shù)及三個常用的高階函數(shù),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-02-02

最新評論

延川县| 安塞县| 黔西| 渝中区| 绥芬河市| 绿春县| 永和县| 莲花县| 阳东县| 大荔县| 四川省| 宜君县| 奉贤区| 上虞市| 金乡县| 日喀则市| 林口县| 枣庄市| 安阳县| 佛冈县| 上虞市| 葵青区| 苏州市| 义乌市| 林周县| 雅安市| 团风县| 永定县| 临江市| 疏附县| 纳雍县| 湘阴县| 永新县| 怀集县| 郓城县| 鸡西市| 舞阳县| 宝坻区| 邹城市| 佛山市| 海晏县|