导入FashionMNIST数据集时报错module 'torchvision.datasets' has no attribute 'FashionMNIS’

在阅读动手学深度学习-pytorch的过程中,发现softmax部分代码需要加载FashionMNIS数据集

书上代码如下:

mnist_train =
torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST',
train=True, download=True, transform=transforms.ToTensor())
mnist_test =
torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST',
train=False, download=True, transform=transforms.ToTensor())

在对上述代码运行之后程序报错:module ‘torchvision.datasets’ has no attribute ‘FashionMNIST’

于是,对pytorch中文文档进行查看,发现pytorch并没有提供这个数据集,铁证如下:
导入FashionMNIST数据集时报错module 'torchvision.datasets' has no attribute 'FashionMNIS’_第1张图片
没有FashionMNIST数据集!!!!!!我人都傻了。这不是搞事吗!!!!!
出于无奈我的手动导入数据集,数据集文件来自github,文件链接如下:FashionMNIST数据集
下载好压缩文件之后,对压缩文件进行解压,解压结果如下:
导入FashionMNIST数据集时报错module 'torchvision.datasets' has no attribute 'FashionMNIS’_第2张图片
然后需要读取解压之后的数据,具体代码我也是参考别人的代码。参考的文章链接如下:

https://blog.csdn.net/a435262767/article/details/102012323

具体代码如下:

导入的模块

import torch
import torchvision
import numpy as np
import os
import sys
import gzip
sys.path.append("..")
import d2lzh_pytorch as d2l

打开读取压缩文件

def data_load(path, kind):
    images_path = os.path.join(path,'%s-images-idx3-ubyte.gz' % kind)
    labels_path = os.path.join(path,'%s-labels-idx1-ubyte.gz' % kind)
    with gzip.open(labels_path,'rb') as lbpath:
        labels = np.frombuffer(lbpath.read(),dtype=np.uint8, offset=8)    
    with gzip.open(images_path,'rb') as impath:
        images = np.frombuffer(impath.read(),dtype=np.uint8, offset=16).reshape(len(labels),784)
    return images, labels

读取转化数据

X_train, y_train = data_load('E:/FashionMNIST','train')
X_test, y_test = data_load('E:/FashionMNIST','t10k')
X_train_tensor = torch.from_numpy(X_train).to(torch.float32).view(-1,1,28,28)*(1/255)
X_test_tensor = torch.from_numpy(X_test).to(torch.float32).view(-1,1,28,28)*(1/255)
y_train_tensor = torch.from_numpy(y_train).to(torch.float32).view(-1,1)
y_test_tensor = torch.from_numpy(y_test).to(torch.float32).view(-1,1)

mnist_train = torch.utils.data.TensorDataset(X_train_tensor, y_train_tensor)
mnist_test = torch.utils.data.TensorDataset(X_test_tensor, y_test_tensor)

batch_size = 256
train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True)
test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False)

然后现在的数据就和书上差不多了,就可以继续学习了

你可能感兴趣的:(动手学深度学习-pytorch,深度学习,python)