import torch
import torchvision
from torch.utils import data
from torchvision import transforms
from d2l import torch as d2l
trans = transforms.ToTensor()
mnist_train = torchvision.datasets.MNIST(
root="../data", train=True, transform=trans, download=False)
mnist_test = torchvision.datasets.MNIST(
root="../data", train=False, transform=trans, download=False)
# scale 是放大倍数
def show_images(imgs, num_rows, num_cols, titles=None, scale=2): #@save
"""绘制图像列表"""
figsize = (num_cols * scale, num_rows * scale)计算新尺寸
_, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize)
axes = axes.flatten()
for i, (ax, img) in enumerate(zip(axes, imgs)):
if torch.is_tensor(img):
# 图片张量
ax.imshow(img.numpy())
else:
# PIL图片
ax.imshow(img)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
if titles:
ax.set_title(titles[i])
return axes
X, y = next(iter(data.DataLoader(mnist_train, batch_size=18)))
show_images(X.reshape(18, 28, 28), 2, 9, titles=np.array(y).tolist());#此处title是列表 list格式
batch_size = 256
def get_dataloader_workers(): #@save
"""使用4个进程来读取数据"""
return 4
# 进程数可删,但是时间给慢,大概十秒左右
train_iter = data.DataLoader(mnist_train, batch_size, shuffle=True,
num_workers=get_dataloader_workers())
timer = d2l.Timer()
for X, y in train_iter:
continue
print(f'{timer.stop():.2f} sec') #1.15 sec
timer = d2l.Timer()
for X, y in train_iter:
continue
print(f'{timer.stop():.2f} sec') #1.07 sec
利用李沐深度学习图片分类写出读取手写数据集(没有训练版本)
最新推荐文章于 2024-09-03 09:37:00 发布