赞
踩
目录
1.1 Fashion-MNIST是一个服装分类数据集,由10个类别的图像组成,分别为t-shirt(T恤)、trouser(裤子)、pullover(套衫)、dress(连衣裙)、coat(外套)、sandal(凉鞋)、shirt(衬衫)、sneaker(运动鞋)、bag(包)和ankle boot(短靴)。
1.2 Fashion‐MNIST由10个类别的图像组成,每个类别由训练数据集(train dataset)中的6000张图像和测试数据 集(test dataset)中的1000张图像组成。因此,训练集和测试集分别包含60000和10000张图像。测试数据集 不会用于训练,只用于评估模型性能。
以下函数用于在数字标签索引及其文本名称之间进行转换。
- # 通过ToTensor实例将图像数据从PIL类型变换成32位浮点数格式,
- # 并除以255使得所有像素的数值均在0~1之间
- trans = transforms.ToTensor()
- mnist_train = torchvision.datasets.FashionMNIST(
- root="../data", train=True, transform=trans, download=True)
- mnist_test = torchvision.datasets.FashionMNIST(
- root="../data", train=False, transform=trans, download=True)
以下函数用于在数字标签索引及其文本名称之间进行转换。
- def get_fashion_mnist_labels(labels): #@save
- """返回Fashion-MNIST数据集的文本标签"""
- text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
- 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
- return [text_labels[int(i)] for i in labels]
- import torch
- import torchvision
- import pylab
- from torch.utils import data
- from torchvision import transforms
- import matplotlib.pyplot as plt
- from d2l import torch as d2l
- import time
-
- batch_size = 256
- num_inputs = 784
- num_outputs = 10
- W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True)
- b = torch.zeros(num_outputs, requires_grad=True)
- num_epochs = 5
-
-
- class Accumulator:
- """在n个变量上累加"""
- def __init__(self, n):
- self.data = [0.0] * n
-
- def add(self, *args):
- self.data = [a + float(b) for a, b in zip(self.data, args)]
-
- def reset(self):
- self.data = [0.0] * len(self.data)
-
- def __getitem__(self, idx):
- return self.data[idx]
-
-
- def accuracy(y_hat, y): #@save
- """计算预测正确的数量"""
- if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
- y_hat = y_hat.argmax(axis=1)
- cmp = y_hat.type(y.dtype) == y
- return float(cmp.type(y.dtype).sum())
-
-
- def cross_entropy(y_hat, y):
- return -torch.log(y_hat[range(len(y_hat)), y])
-
-
- def softmax(X):
- X_exp = torch.exp(X)
- partition = X_exp.sum(1, keepdim=True)
- return X_exp/partition
-
-
- def net(X):
- return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) + b)
-
-
- def get_dataloader_workers():
- """使用一个进程来读取的数据"""
- return 1
-
-
- def get_fashion_mnist_labels(labels):
- """返回Fashion-MNIST数据集的文本标签"""
- #共10个类别
- text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
- return [text_labels[int(i)] for i in labels]
-
-
- def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5):
- """画一系列图片"""
- figsize = (num_cols * scale, num_rows * scale)
- _, axes = plt.subplots(num_rows, num_cols, figsize=figsize)
- for i, (img, label) in enumerate(zip(imgs, titles)):
- xloc, yloc = i//num_cols, i % num_cols
- if torch.is_tensor(img):
- # 图片张量
- axes[xloc, yloc].imshow(img.reshape((28, 28)).numpy())
- else:
- # PIL图片
- axes[xloc, yloc].imshow(img)
- # 设置标题并取消横纵坐标上的刻度
- axes[xloc, yloc].set_title(label)
- plt.xticks([], ())
- axes[xloc, yloc].set_axis_off()
- pylab.show()
-
-
- def load_data_fashion_mnist(batch_size, resize=None):
- """下载Fashion-MNIST数据集,然后将其加载到内存中"""
- trans = transforms.ToTensor()
- if resize:
- trans.insert(0, transforms.Resize(resize))
- mnist_train = torchvision.datasets.FashionMNIST(root='../data', train=True, transform=trans, download=True)
- mnist_test = torchvision.datasets.FashionMNIST(root='../data', train=False, transform=trans, download=True)
- return (data.DataLoader(mnist_train, batch_size, shuffle=True, num_workers=get_dataloader_workers()),
- data.DataLoader(mnist_test, batch_size, shuffle=False, num_workers=get_dataloader_workers()))
-
-
- def evaluate_accuracy(net, data_iter):
- """计算在指定数据集上模型的精度"""
- if isinstance(net, torch.nn.Module):
- net.eval() # 将模型设置为评估模式
- metric = Accumulator(2) # 正确预测数、预测总数
- with torch.no_grad():
- for X, y in data_iter:
- metric.add(accuracy(net(X), y), y.numel())
- return metric[0] / metric[1]
-
-
- def updater(batch_size):
- lr = 0.1
- return d2l.sgd([W, b], lr, batch_size)
-
-
- def train_epoch_ch3(net, train_iter, loss, updater):
- if isinstance(net, torch.nn.Module):
- net.train()
- metric = Accumulator(3)
- for X, y in train_iter:
- y_hat = net(X)
- lo = loss(y_hat, y)
- if isinstance(updater, torch.optim.Optimizer):
- updater.zero_grad()
- lo.backward()
- updater.step()
- metric.add(float(lo)*len(y), accuracy(y_hat, y), y.size().numel())
- else:
- lo.sum().backward()
- updater(X.shape[0])
- metric.add(float(lo.sum()), accuracy(y_hat, y), y.numel())
- return metric[0] / metric[2], metric[1] / metric[2]
-
-
- class Animator: #@save
- """绘制数据"""
- def __init__(self, legend=None):
- self.legend = legend
- self.X = [[], [], []]
- self.Y = [[], [], []]
-
- def add(self, x, y):
- # 向图表中添加多个数据点
- if not hasattr(y, "__len__"):
- y = [y]
- n = len(y)
- if not hasattr(x, "__len__"):
- x = [x] * n
- for i, (a, b) in enumerate(zip(x, y)):
- if a is not None and b is not None:
- self.X[i].append(a)
- self.Y[i].append(b)
-
- def show(self):
- plt.plot(self.X[0], self.Y[0], 'r--')
- plt.plot(self.X[1], self.Y[1], 'g--')
- plt.plot(self.X[2], self.Y[2], 'b--')
- plt.legend(self.legend)
- plt.xlabel('epoch')
- plt.ylabel('value')
- plt.title('Visual')
- plt.show()
-
-
- def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater): #@save
- """训练模型"""
- animator = Animator(legend=['train loss', 'train acc', 'test acc'])
- for epoch in range(num_epochs):
- train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
- train_loss, train_acc = train_metrics
- test_acc = evaluate_accuracy(net, test_iter)
- animator.add(epoch + 1, train_metrics + (test_acc,))
- print(f'epoch: {epoch+1},train_loss:{train_loss:.4f}, train_acc:{train_acc:.4f}, test_acc:{test_acc:.4f}')
- animator.show()
-
-
- def predict_ch3(net, test_iter, n=12):
- """预测标签"""
- for X, y in test_iter:
- break
- trues = d2l.get_fashion_mnist_labels(y)
- preds = d2l.get_fashion_mnist_labels(net(X).argmax(axis=1))
- titles = [true +'\n' + pred for true, pred in zip(trues, preds)]
- show_images(
- X[0:n].reshape((n, 28, 28)), 2, int(n/2), titles=titles[0:n])
-
-
- if __name__ == '__main__':
- train_iter, test_iter = load_data_fashion_mnist(batch_size)
- train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
- predict_ch3(net, test_iter)
-
分类效果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。