DL之DNN:自定义2层神经网络TwoLayerNet模型(封装为层级结构)利用MNIST数据集进行训练、GC对比
DL之DNN:自定義2層神經網絡TwoLayerNet模型(封裝為層級結構)利用MNIST數據集進行訓練、GC對比
導讀
? ? ? ? ? 神經網絡算法封裝為層級結構的作用。在神經網絡算法中,通過將神經網絡的組成元素實現為層,可以高效地計算梯度(反向傳播法)。通過比較數值微分和誤差反向傳播法的結果,可以確認誤差反向傳播法的實現是否正確(梯度確認)。
?
?
目錄
輸出結果
設計思路
核心代碼
代碼實現過程錯誤記錄
?
?
?
輸出結果
?
設計思路
?
核心代碼
class TwoLayerNet:def __init__(self, input_size, hidden_size, output_size, weight_init_std = 0.01):self.params = {}self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)self.params['b1'] = np.zeros(hidden_size)self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size) self.params['b2'] = np.zeros(output_size)self.layers = OrderedDict()self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])self.layers['Relu1'] = Relu()self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])self.lastLayer = SoftmaxWithLoss()def predict(self, x):for layer in self.layers.values():x = layer.forward(x)return x# x:輸入數據, t:監督數據def loss(self, x, t):y = self.predict(x)return self.lastLayer.forward(y, t)def accuracy(self, x, t):y = self.predict(x)y = np.argmax(y, axis=1)if t.ndim != 1 : t = np.argmax(t, axis=1)accuracy = np.sum(y == t) / float(x.shape[0])return accuracydef gradient(self, x, t):self.loss(x, t)dout = 1dout = self.lastLayer.backward(dout)layers = list(self.layers.values())layers.reverse()for layer in layers:dout = layer.backward(dout)grads = {}grads['W1'], grads['b1'] = self.layers['Affine1'].dW, self.layers['Affine1'].dbgrads['W2'], grads['b2'] = self.layers['Affine2'].dW, self.layers['Affine2'].dbreturn gradsnetwork_batch = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)grad_numerical = network_batch.numerical_gradient_api(x_batch, t_batch) grad_backprop = network_batch.gradient(x_batch, t_batch)?
?
?
代碼實現過程錯誤記錄
出現錯誤,待解決!!!
Traceback (most recent call last):
? File "F:\File_Python\Python_daydayup\190316.py", line 281, in <module>
? ? grad = network.gradient(x_batch, t_batch) ? ? ? ? ? ??
? File "F:\File_Python\Python_daydayup\190316.py", line 222, in gradient
? ? self.loss(x, t)
? File "F:\File_Python\Python_daydayup\190316.py", line 193, in loss
? ? return self.lastLayer.forward(y, t) # ? ? ? ? ☆★☆★☆★☆★☆★☆★☆★☆★☆★☆★☆★☆★☆★☆ ? ------部分更改
? File "F:\File_Python\Python_daydayup\190316.py", line 132, in forward
? ? self.loss = cross_entropy_error(self.y, self.t)
? File "F:\File_Python\Python_daydayup\190316.py", line 39, in cross_entropy_error
? ? return -np.sum(np.log(y[np.arange(batch_size), t.astype('int64')] + 1e-7)) / batch_size ? ? ? ? ?#t.astype('int64')
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (100,) (100,10)?
?
?
?
相關文章
DL之DNN:自定義2層神經網絡TwoLayerNet模型(層級結構更高效)算法對MNIST數據集進行訓練、預測
?
總結
以上是生活随笔為你收集整理的DL之DNN:自定义2层神经网络TwoLayerNet模型(封装为层级结构)利用MNIST数据集进行训练、GC对比的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HighNewTech:支付宝全球首发5
- 下一篇: 成功解决IndexError: arra