【Pytorch】数据集的加载和处理(一)
Pytorch中张量可以是一维、二维、三维或者更高维度的数据结构。一维张量类似于向量,二维张量类似于矩阵,三维张量类似一系列矩阵的堆叠。
目录
将张量包装为数据集
导入MNIST训练数据集并提取数据和标签
import torch
import torchvision
from torchvision import datasets
train_data=datasets.MNIST("./data",train=True,download=True)
x_train, y_train=train_data.data,train_data.targets
导入MNIST验证数据集并提取数据和标签
val_data=datasets.MNIST("./data", train=False, download=True)
x_val,y_val=val_data.data, val_data.targets
使用 TensorDataset类将张量包装为数据集
from torch.utils.data import TensorDataset
train_ds = TensorDataset(x_train, y_train)
val_ds = TensorDataset(x_val, y_val)
for x,y in train_ds:
print(x.shape,y.item())
break
创建数据加载器
通过DataLoader从数据集创建数据加载器
from torch.utils.data import DataLoader
train_dl = DataLoader(train_ds, batch_size=100)
val_dl = DataLoader(val_ds, batch_size=100)
for xb,yb in train_dl:
print(xb.shape)
print(yb.shape)
break
数据转换(图像转换)
通过 transform 类进行简单的图像转换
导入库和训练数据集
import torchvision
import matplotlib.pyplot as plt
from torchvision import datasets
from torchvision import transforms
train_data=datasets.MNIST("./data", train=True, download=True)
借助transform类定义旋转
data_transform = transforms.Compose
([
transforms.RandomHorizontalFlip(p=1),
transforms.RandomVerticalFlip(p=1),
transforms.ToTensor(),
])
对训练数据集中图像进行旋转并打印对比
img = train_data[5][0]
img_tr=data_transform(img)
img_tr_np=img_tr.numpy()
plt.subplot(1,2,1)
plt.imshow(img,cmap="gray")
plt.title("original")
plt.subplot(1,2,2)
plt.imshow(img_tr_np[0],cmap="gray");
plt.title("transformed 180")