現(xiàn)在,定義我們的ConvNet體系結(jié)構(gòu),然后使用單GPU/CPU來訓練它(我有一個非常廉價的GPU,但它很有用)
net1 = NeuralNet(
layers=[('input', layers.InputLayer),
('conv2d1', layers.Conv2DLayer),
('maxpool1', layers.MaxPool2DLayer),
('conv2d2', layers.Conv2DLayer),
('maxpool2', layers.MaxPool2DLayer),
('dropout1', layers.DropoutLayer),
('dense', layers.DenseLayer),
('dropout2', layers.DropoutLayer),
('output', layers.DenseLayer),
],
# input layer
input_shape=(None, 1, 28, 28),
# layer conv2d1
conv2d1_num_filters=32,
conv2d1_filter_size=(5, 5),
conv2d1_nonlinearity=lasagne.nonlinearities.rectify,
conv2d1_W=lasagne.init.GlorotUniform(),
# layer maxpool1
maxpool1_pool_size=(2, 2),
# layer conv2d2
conv2d2_num_filters=32,
conv2d2_filter_size=(5, 5),
conv2d2_nonlinearity=lasagne.nonlinearities.rectify,
# layer maxpool2
maxpool2_pool_size=(2, 2),
# dropout1
dropout1_p=0.5,
# dense
dense_num_units=256,
dense_nonlinearity=lasagne.nonlinearities.rectify,
# dropout2
dropout2_p=0.5,
# output
output_nonlinearity=lasagne.nonlinearities.softmax,
output_num_units=10,
# optimization method params
update=nesterov_momentum,
update_learning_rate=0.01,
update_momentum=0.9,
max_epochs=10,
verbose=1,
)
# Train the network
nn = net1.fit(X_train, y_train)
如你所視,在layers的參數(shù)中,我們定義了一個有層名稱/類型的元組字典,然后定義了這些層的參數(shù)。在這里,我們的體系結(jié)構(gòu)使用的是兩個卷積層,兩個池化層,一個全連接層(稠密層,dense layer)和一個輸出層。在一些層之間也會有dropout層,dropout層是一個正則化矩陣,隨機的設(shè)置輸入值為零來避免過擬合(見下圖)。

Dropout層效果
調(diào)用訓練方法后,nolearn包將會顯示學習過程的狀態(tài),我的機器使用的是低端的的GPU,得到的結(jié)果如下:
# Neural Network with 160362 learnable parameters
## Layer information
# name size
--- -------- --------
0 input 1x28x28
1 conv2d1 32x24x24
2 maxpool1 32x12x12
3 conv2d2 32x8x8
4 maxpool2 32x4x4
5 dropout1 32x4x4
6 dense 256
7 dropout2 256
8 output 10
epoch train loss valid loss train/val valid acc dur
------- ------------ ------------ ----------- --------- ---
1 0.85204 0.16707 5.09977 0.95174 33.71s
2 0.27571 0.10732 2.56896 0.96825 33.34s
3 0.20262 0.08567 2.36524 0.97488 33.51s
4 0.16551 0.07695 2.15081 0.97705 33.50s
5 0.14173 0.06803 2.08322 0.98061 34.38s
6 0.12519 0.06067 2.06352 0.98239 34.02s
7 0.11077 0.05532 2.00254 0.98427 33.78s
8 0.10497 0.05771 1.81898 0.98248 34.17s
9 0.09881 0.05159 1.91509 0.98407 33.80s
10 0.09264 0.04958 1.86864 0.98526 33.40s
正如你看到的,最后一次的精度可以達到0.98526,是這10個單元訓練中的一個相當不錯的性能。
預測和混淆矩陣
現(xiàn)在,我們使用這個模型來預測整個測試集:
preds = net1.predict(X_test)
我們還可以繪制一個混淆矩陣來檢查神經(jīng)網(wǎng)絡(luò)的分類性能:
cm = confusion_matrix(y_test, preds)
plt.matshow(cm)
plt.title('Confusion matrix')
plt.colorbar()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
上面的代碼將繪制下面的混淆矩陣:

混淆矩陣
如你所視,對角線上的分類更密集,表明我們的分類器有一個良好的性能。
過濾器的可視化
我們還可以從第一個卷積層中可視化32個過濾器:
visualize.plot_conv_weights(net1.layers_['conv2d1'])
上面的代碼將繪制下面的過濾器:

第一層的5x5x32過濾器
如你所視,nolearn的plot_conv_weights函數(shù)在我們指定的層中繪制出了所有的過濾器。
Theano層的功能和特征提取
電子發(fā)燒友App

















評論