torchvision​包下载MNIST数据集

  • Post author:
  • Post category:其他


TorchVision是PyTorch项目的一部分,torchvision软件包包括:流行的数据集、模型架构以及

计算机视觉的常见图像转换。

##bash安装
pip install torchvision 

import torch
import numpy as np
from torchvision.datasets import mnist
import torchvision.transforms as transforms  #公开数据集的预处理库,格式转换
import matplotlib.pyplot as plt

## 下载训练数据
train_data = mnist.MNIST('./data',train=True,download = True)
print(train_data)
print(type(train_data)) # <class 'torchvision.datasets.mnist.MNIST'>

print(train_data[0][0]) # 第一个图片数据
print(type(train_data[0][0])) # <class 'PIL.Image.Image'>
train_X_1 = torchvision.transforms.ToTensor()(train_data[0][0]) # 转成tensor
print(train_X_1.size()) # torch.Size([1, 28, 28])

print(train_data[0][1]) # 第一个图片的label
print(type(train_data[0][1])) # <class 'int'>

## 下载训练数据,tensor转化
train_data = mnist.MNIST(root = "./data",
                           train = True,
                           transform = transforms.ToTensor(),
                           download = True)
 
## 下载测试数据
test_data = mnist.MNIST(root = "./datat",
                           train = False,
                           transform = transforms.ToTensor(),
                           download = True)
 
print(train_data)
# 第一个图片数据(tensor)和label
image, label = train_data[0]
#print(type(image))
#print(type(label))
print("torch image shape:", image.size())
print("torch image shape:", image.shape)
print("torch image label:", label)

print("size=", len(train_data))
print("")
print(test_data)
print("size=", len(test_data))

# 变成灰色
image = torchvision.utils.make_grid(image)

print("torch gray image shape:", image.shape)

# 通道维度放到最后,才能显示图片
image = image.numpy().transpose(1,2,0) 
print("numpy image shape:", image.shape)
print("numpy image label:", label)

#print(image)
# 加上噪音
#std = [1.]
#mean = [1.]
#image = image * std + mean


#显示原图
plt.imshow(image)
plt.show()

# 批量数据读取
train_loader = torch.utils.data.DataLoader(dataset = train_data,
                                           batch_size = 16,
                                           shuffle = True)

imgs, labels = next(iter(train_loader))
print(imgs.shape)
print(labels.shape)

#imgs = torchvision.utils.make_grid(imgs)
#imgs = imgs.numpy().transpose(1,2,0)

imgs = imgs.numpy().transpose(0,2,3,1)
#print(imgs)
imgs = np.hstack(imgs)
#imgs = imgs.reshape(28*16,28, 1)

print(imgs.shape)
print(labels.shape)

plt.imshow(imgs)
plt.show()


参考:


https://pytorch.org/vision/stable/index.html



https://blog.csdn.net/baidu_38797690/article/details/122513894



版权声明:本文为qq_27390023原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。