torchvision​包下载MNIST数据集

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值