数据集建立和导入


title: Pytorch学习笔记-数据集建立和导入

学习笔记和实现代码详见如下:

“”"
官方教程:
训练集和测试集下载
“”"
import torch
from torch.utils.data import Dataset
from torchvision import datasets
from torchvision.transforms import ToTensor
import matplotlib.pyplot as plt

Loading a Dataset

training_data = datasets.FashionMNIST(
root=“./data/”,
train=True,
download=True,
transform=ToTensor()
)

test_data = datasets.FashionMNIST(
root=“./data/”,
train=False,
download=True,
transform=ToTensor()
)

Iterating and Visualizing the Dataset 迭代和可视化数据集

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] # tensor格式的图片,label标签
figure.add_subplot(rows, cols, i)
plt.title(labels_map[label])
plt.axis(“off”)
plt.imshow(img.squeeze(), cmap=“gray”)
plt.show()

Creating a Custom Dataset for your files

import os
import pandas as pd
from torchvision.io import read_image

class CustomImageDataset(Dataset):
“”"
自定义Dataset类必须实现三个函数:initlen__和__getitem
看看这个实现;
FashionMNIST图像存储在目录img_dir中,
它们的标签分别存储在CSV文件annotations_file中
“”"

def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
    """
    __init__函数在实例化Dataset对象时运行一次。
    我们初始化包含图像、注释文件和两种转换的目录(下一节将详细介绍)。
    """
    self.img_labels = pd.read_csv(annotations_file)
    self.img_dir = img_dir
    self.transform = transform
    self.target_transform = target_transform

def __len__(self):
    """
    __len__函数返回数据集中的样本数量。
    """
    return len(self.img_labels)

def __getitem__(self, idx):
    """
    __getitem__函数从给定索引idx的数据集中加载并返回一个示例。
    根据索引,它确定图像在磁盘上的位置,使用read_image将其转换为一个张量,并从self中的csv数据中检索相应的标签。
    Img_labels,调用它们上的转换函数(如果适用),并在一个元组中返回张量image和相应的标签。
    """
    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

Preparing your data for training with DataLoaders

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)

Iterate through the DataLoader

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}")

“”"
/**

  •                   _ooOoo_
    
    •               o8888888o
      
    •               88" . "88
      
    •               (| -_- |)
      
    •                O\ = /O
      
    •            ____/`---'\____
      
    •          .   ' \\| |// `.
      
    •           / \\||| : |||// \
      
    •         / _||||| -:- |||||- \
      
    •           | | \\\ - /// | |
      
    •         | \_| ''\---/'' | |
      
    •          \ .-\__ `-` ___/-. /
      
    •       ___`. .' /--.--\ `. . __
      
    •    ."" '< `.___\_<|>_/___.' >'"".
      
    •   | | : `- \`.;`\ _ /`;.`/ - ` : | |
      
    •     \ \ `-. \_ __\ /__ _/ .-` / /
      
    • -.____-._/.-`__.-’
    •                `=---='
      
    •      佛祖保佑             永无BUG
      
  • */

“”"

你可能感兴趣的:(Pytorch,python,深度学习,pytorch)