Pytorch: 卷积神经网络识别 Fashion-MNIST
Copyright: Jingmin Wei, Pattern Recognition and Intelligent System, School of Artificial and Intelligence, Huazhong University of Science and Technology
本教程不商用,仅供学习和参考交流使用,如需转载,请联系本人。
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
import copy
import time
import torch
import torch.nn as nn
from torch.optim import Adam
import torch.utils.data as Data
from torchvision import transforms
from torchvision.datasets import FashionMNIST
本章将通过自己搭建卷积神经网络识别 Fashion-MNIST ,并对结果进行可视化分析。
图像数据准备
调用 sklearn 的 datasets 模块的 FashionMNIST 的 API 函数读取。
# 使用 FashionMNIST 数据,准备训练数据集
train_data = FashionMNIST(
root = './data/FashionMNIST',
train = True,
transform = transforms.ToTensor(),
download = False
)
# 定义一个数据加载器
train_loader = Data.DataLoader(
dataset = train_data, # 数据集
batch_size = 64, # 批量处理的大小
shuffle = False, # 不打乱数据
num_workers = 2, # 两个进程
)
# 计算 batch 数
print(len(train_loader))
938
上述程序块定义了一个数据加载器,批量的数据块为 64.
接下来我们进行数据可视化分析,将 tensor 数据转为 numpy 格式,然后利用 imshow 进行可视化。
# 获得 batch 的数据
for step, (b_x, b_y) in enumerate(train_loader):
if step > 0:
break
# 可视化一个 batch 的图像
batch_x = b_x.squeeze().numpy()
batch_y = b_y.numpy()
label = train_data.classes
label[0] = 'T-shirt'
plt.figure(figsize = (12, 5))
for i in np.arange(len(batch_y)):
plt.subplot(4, 16, i + 1)
plt.imshow(batch_x[i, :, :], cmap = plt.cm.gray)
plt.title(label[batch_y[i]], size = 9)
plt.axis('off')
plt.subplots_adjust(wspace = 0.05)
然后我们处理测试集样本,将所有样本看成一个整体,作为一个 batch 测试。即导入了 10000 10000 10000 张 28 × 28 28\times28 28×28 的图像
# 处理测试集
test_data = FashionMNIST(
root = './data/FashionMNIST',
train = False, # 不使用训练数据集
download = False
)
# 为数据添加一个通道维度,并且取值范围归一化
test_data_x = test_data.data.type(torch.FloatTensor) / 255.0
test_data_x = torch.unsqueeze(test_data_x, dim = 1)
test_data_y = test_data.targets # 测试集标签
print(test_data_x.shape)
print