时间轴网站,wordpress 修改导航,室内设计师收入,seo引擎优化教程目录
1、数据集#xff1a;
2、完整代码 1、数据集#xff1a;
1.1 Fashion-MNIST是一个服装分类数据集#xff0c;由10个类别的图像组成#xff0c;分别为t-shirt#xff08;T恤#xff09;、trouser#xff08;裤子#xff09;、pullover#xff08;套衫#xf…目录
1、数据集
2、完整代码 1、数据集
1.1 Fashion-MNIST是一个服装分类数据集由10个类别的图像组成分别为t-shirtT恤、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使得所有像素的数值均在01之间
trans transforms.ToTensor()
mnist_train torchvision.datasets.FashionMNIST(root../data, trainTrue, transformtrans, downloadTrue)
mnist_test torchvision.datasets.FashionMNIST(root../data, trainFalse, transformtrans, downloadTrue)
以下函数用于在数字标签索引及其文本名称之间进行转换。
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]
2、完整代码
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 timebatch_size 256
num_inputs 784
num_outputs 10
W torch.normal(0, 0.01, size(num_inputs, num_outputs), requires_gradTrue)
b torch.zeros(num_outputs, requires_gradTrue)
num_epochs 5class Accumulator:在n个变量上累加def __init__(self, n):self.data [0.0] * ndef 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(axis1)cmp y_hat.type(y.dtype) yreturn 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, keepdimTrue)return X_exp/partitiondef net(X):return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) b)def get_dataloader_workers():使用一个进程来读取的数据return 1def 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, titlesNone, scale1.5):画一系列图片figsize (num_cols * scale, num_rows * scale)_, axes plt.subplots(num_rows, num_cols, figsizefigsize)for i, (img, label) in enumerate(zip(imgs, titles)):xloc, yloc i//num_cols, i % num_colsif 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, resizeNone):下载Fashion-MNIST数据集然后将其加载到内存中trans transforms.ToTensor()if resize:trans.insert(0, transforms.Resize(resize))mnist_train torchvision.datasets.FashionMNIST(root../data, trainTrue, transformtrans, downloadTrue)mnist_test torchvision.datasets.FashionMNIST(root../data, trainFalse, transformtrans, downloadTrue)return (data.DataLoader(mnist_train, batch_size, shuffleTrue, num_workersget_dataloader_workers()),data.DataLoader(mnist_test, batch_size, shuffleFalse, num_workersget_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.1return 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, legendNone):self.legend legendself.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] * nfor 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_metricstest_acc evaluate_accuracy(net, test_iter)animator.add(epoch 1, train_metrics (test_acc,))print(fepoch: {epoch1},train_loss:{train_loss:.4f}, train_acc:{train_acc:.4f}, test_acc:{test_acc:.4f})animator.show()def predict_ch3(net, test_iter, n12):预测标签for X, y in test_iter:breaktrues d2l.get_fashion_mnist_labels(y)preds d2l.get_fashion_mnist_labels(net(X).argmax(axis1))titles [true \n pred for true, pred in zip(trues, preds)]show_images(X[0:n].reshape((n, 28, 28)), 2, int(n/2), titlestitles[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)
分类效果