1. 在所有其他參數保持不變的情況下,更改超參數num_hiddens的值,并查看此超參數的變化對結果有何影響。確定此超參數的最佳值。
通過改變隱藏層的數量,導致就是函數擬合復雜度下降,隱藏層過多可能導致過擬合,而過少導致欠擬合。
我們將層數改為128可得:
2. 嘗試添加更多的隱藏層,并查看它對結果有何影響。
過擬合,導致測試機精確度下降。
3. 改變學習速率會如何影響結果?保持模型架構和其他超參數(包括輪數)不變,學習率設置為多少會帶來最好的結果?
過高的學習率導致,梯度跨度過大,使得降低不到對應的駐點。
過低的學習率導致訓練緩慢,需要增加epoch。
在訓練輪數不變的情況下,我們可以通過for 設置不同的學習率找出最合適的學習率。一般來說設置為0.01或者0.1足以
4. 通過對所有超參數(學習率、輪數、隱藏層數、每層的隱藏單元數)進行聯合優化,可以得到的最佳結果是什么?
跑了一次學習率lr=0.01的情況:
需要大量的訓練,但是目前我訓練結果是學習率lr=0.1、輪數是num_epochs=10,隱藏層數為1,隱藏層數單元num_hiddens=128。
5. 描述為什么涉及多個超參數更具挑戰性。
因為組合的情況更多,當層數越多時,訓練時間也更多,這玩意就是煉丹了,看你自己的GPU還有時間、運氣。
6. 如果想要構建多個超參數的搜索方法,請想出一個聰明的策略。
套用for 循環暴力破解,時間上肯定慢的要死,我們可以先固定其他變量,挑選一個變量尋找最優解,以此類推對所有的超參數這樣使用,但是這種做法肯定不是最優的,只是能夠較好的找出比較好的超參數。
由于學校窮逼所以沒有閑置GPU服務器,所有的模型只能在colab上進行運行,其中遇到了d2l的版本對應問題,所以對于d2l.train_ch3跑不起來,只能使用自寫進行替代如下:
import torch.nn
from d2l import torch as d2l
from IPython import displayclass Accumulator:"""在n個變量上累加"""def __init__(self, n):self.data = [0.0] * n # 創建一個長度為 n 的列表,初始化所有元素為0.0。def add(self, *args): # 累加self.data = [a + float(b) for a, b in zip(self.data, args)]def reset(self): # 重置累加器的狀態,將所有元素重置為0.0self.data = [0.0] * len(self.data)def __getitem__(self, idx): # 獲取所有數據return self.data[idx]def accuracy(y_hat, y):"""計算正確的數量:param y_hat::param y::return:"""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) == yreturn float(cmp.type(y.dtype).sum())def evaluate_accuracy(net, data_iter):"""計算指定數據集的精度:param net::param data_iter::return:"""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]class Animator:"""在動畫中繪制數據"""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, fmtsdef add(self, x, y):"""向圖表中添加多個數據點:param x::param y::return:"""if not hasattr(y, "__len__"):y = [y]n = len(y)if not hasattr(x, "__len__"):x = [x] * nif 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)def train_epoch_ch3(net, train_iter, loss, updater):"""訓練模型一輪:param net:是要訓練的神經網絡模型:param train_iter:是訓練數據的數據迭代器,用于遍歷訓練數據集:param loss:是用于計算損失的損失函數:param updater:是用于更新模型參數的優化器:return:"""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.mean().backward() # 方法用于計算損失的平均值updater.step()else:# 使用定制(自定義)的優化器和損失函數l.sum().backward()updater(X.shape())metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())# 返回訓練損失和訓練精度return metric[0] / metric[2], metric[1] / metric[2]def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):"""訓練模型():param net::param train_iter::param test_iter::param loss::param num_epochs::param updater::return:"""animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],legend=['train loss', 'train acc', 'test acc'])for epoch in range(num_epochs):trans_metrics = train_epoch_ch3(net, train_iter, loss, updater)test_acc = evaluate_accuracy(net, test_iter)animator.add(epoch + 1, trans_metrics + (test_acc,))train_loss, train_acc = trans_metricsprint(trans_metrics)def predict_ch3(net, test_iter, n=6):"""進行預測:param net::param test_iter::param n::return:"""global X, yfor X, y in test_iter:breaktrues = 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])d2l.plt.show()