1.去PyTorch官网上查找Dataloader的文档
使用测试集的原因是测试集样本数更少,运行起来时间会短一些(指用DataLoader遍历的时间):
python
import torchvision
# 准备的测试数据集
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
test_data = torchvision.datasets.CIFAR10("./dataset", train=False, transform=torchvision.transforms.ToTensor())
test_loader = DataLoader(dataset=test_data, batch_size=64, shuffle=True, num_workers=0, drop_last=False)
# 测试数据中的第一张图片
img, target = test_data[0]
print(img.shape)
print(target)
writer = SummaryWriter("dataloader")
step = 0
for data in test_loader:
imgs, targets = data
# print(imgs.shape)
# print(targets)
writer.add_images("test_data", imgs, step)
step = step + 1
writer.close()
drop_last参数
windows系统下如果出现BrokenPipeError的错误,可以考虑将 num_workers设置为0
2.采样器默认是随机采样
python
import torchvision
# 准备的测试数据集
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
test_data = torchvision.datasets.CIFAR10("./dataset", train=False, transform=torchvision.transforms.ToTensor())
test_loader = DataLoader(dataset=test_data, batch_size=64, shuffle=True, num_workers=0, drop_last=True)
# 测试数据中的第一张图片
img, target = test_data[0]
print(img.shape)
print(target)
writer = SummaryWriter("dataloader")
for epoch in range(2):
step = 0
for data in test_loader:
imgs, targets = data
# print(imgs.shape)
# print(targets)
writer.add_images("Epoch:{}".format(epoch), imgs, step)
step = step + 1
writer.close()
用TensorBoard展示图片
①注意要用add_images而不是之前用过的add_image
②一定要等到程序运行结束了再在Terminal(终端)里使用tensorboard命令,不然会出现图片加载不全的情况!可以在程序末尾加一行语句来打印程序结束。