一、從零開始實現
1.1 首先引入Fashion-MNIST數據集
1 import torch 2 from IPython import display 3 from d2l import torch as d2l 4 5 batch_size = 256 6 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
1.2 初始化模型參數
原始圖像中每個樣本都是28*28的,所以要展平每個圖像成長度為784的向量。
權重784*10,偏置1*10
1 num_inputs = 784 2 num_outputs = 10 3 4 W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True) 5 b = torch.zeros(num_outputs, requires_grad=True)
1.3 定義softmax操作
如果為0則留下一行,為1則留下一列
X = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
X.sum(0, keepdim=True), X.sum(1, keepdim=True)
1 def softmax(X): 2 X_exp = torch.exp(X) 3 partition = X_exp.sum(1, keepdim=True) 4 return X_exp / partition # 這里應用了廣播機制
1 X = torch.normal(0, 1, (2, 5)) 2 X_prob = softmax(X) 3 X_prob, X_prob.sum(1)
1.4 模型定義
-1 的地方為批次, W.shape[0]為輸入的維度
1 def net(X): 2 return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) + b)
1.5 損失函數
通過 y 來獲取 y_hat 中的值
1 y = torch.tensor([0, 2]) 2 y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]]) 3 y_hat[[0, 1], y]
學會了以上的操作我們就可以用一行來實現交叉熵損失函數
def cross_entropy(y_hat, y): return -torch.log(y_hat[range(len(y_hat)), y]) cross_entropy(y_hat, y)
1.6 分類准確率
假設y_hat是一個矩陣,第二個維度存儲每個類的預測分數。使用argmax獲得每行中的最大元素。
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())
在評估模式的時候不計算梯度,只做前向傳遞
1 def evaluate_accuracy(net, data_iter): #@save 2 """計算在指定數據集上模型的精度。""" 3 if isinstance(net, torch.nn.Module): 4 net.eval() # 將模型設置為評估模式 5 metric = Accumulator(2) # 正確預測數、預測總數 6 for X, y in data_iter: 7 metric.add(accuracy(net(X), y), y.numel()) 8 return metric[0] / metric[1]
關於用於對多個變量進行累加的Accumulator類的實現
1 class Accumulator: #@save 2 """在`n`個變量上累加。""" 3 def __init__(self, n): 4 self.data = [0.0] * n 5 6 def add(self, *args): 7 self.data = [a + float(b) for a, b in zip(self.data, args)] 8 9 def reset(self): 10 self.data = [0.0] * len(self.data) 11 12 def __getitem__(self, idx): 13 return self.data[idx]
由於隨機權重初始化net模型,所以准確率近似於隨機猜測
1 evaluate_accuracy(net, test_iter)
1.7 訓練
updater
是更新模型參數的常用函數,它接受批量大小作為參數。它可以是封裝的d2l.sgd
函數,也可以是框架的內置優化函數。
def train_epoch_ch3(net, train_iter, loss, updater): #@save """訓練模型一個迭代周期(定義見第3章)。""" # 將模型設置為訓練模式 if isinstance(net, torch.nn.Module): net.train() # 訓練損失總和、訓練准確度總和、樣本數 metric = Accumulator(3) for X, y in train_iter: # 計算梯度並更新參數 y_hat = net(X) l = loss(y_hat, y) if isinstance(updater, torch.optim.Optimizer): # 使用PyTorch內置的優化器和損失函數 updater.zero_grad() # 計算梯度 l.backward() # 更新參數 updater.step() metric.add( float(l) * len(y), accuracy(y_hat, y), y.size().numel()) else: # 使用定制的優化器和損失函數 l.sum().backward() updater(X.shape[0]) metric.add(float(l.sum()), accuracy(y_hat, y), y.numel()) # 返回訓練損失和訓練准確率 return metric[0] / metric[2], metric[1] / metric[2]
輔助函數
class Animator: #@save """在動畫中繪制數據。""" def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1, figsize=(3.5, 2.5)): # 增量地繪制多條線 if legend is None: legend = [] d2l.use_svg_display() self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize) if nrows * ncols == 1: self.axes = [self.axes,] # 使用lambda函數捕獲參數 self.config_axes = lambda: d2l.set_axes(self.axes[ 0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend) self.X, self.Y, self.fmts = None, None, fmts def add(self, x, y): # 向圖表中添加多個數據點 if not hasattr(y, "__len__"): y = [y] n = len(y) if not hasattr(x, "__len__"): x = [x] * n if not self.X: self.X = [[] for _ in range(n)] if not self.Y: self.Y = [[] for _ in range(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) self.axes[0].cla() for x, y, fmt in zip(self.X, self.Y, self.fmts): self.axes[0].plot(x, y, fmt) self.config_axes() display.display(self.fig) display.clear_output(wait=True)
進行num_epochs個迭代周期的訓練,每個迭代周期結束利用test_iter訪問到的測試數據集對模型進行評估。
1 def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater): #@save 2 """訓練模型(定義見第3章)。""" 3 animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9], 4 legend=['train loss', 'train acc', 'test acc']) 5 for epoch in range(num_epochs): 6 train_metrics = train_epoch_ch3(net, train_iter, loss, updater) 7 test_acc = evaluate_accuracy(net, test_iter) 8 animator.add(epoch + 1, train_metrics + (test_acc,)) 9 train_loss, train_acc = train_metrics 10 assert train_loss < 0.5, train_loss 11 assert train_acc <= 1 and train_acc > 0.7, train_acc 12 assert test_acc <= 1 and test_acc > 0.7, test_acc
1 lr = 0.1 2 3 def updater(batch_size): 4 return d2l.sgd([W, b], lr, batch_size) 5 6 num_epochs = 10 7 train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
1.8 預測
def predict_ch3(net, test_iter, n=6): #@save """預測標簽(定義見第3章)。""" # 拿出一個樣本 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)] d2l.show_images(X[0:n].reshape((n, 28, 28)), 1, n, titles=titles[0:n]) predict_ch3(net, test_iter)