Keras实现LeNet-5网络,与可视化网络
生活随笔
收集整理的這篇文章主要介紹了
Keras实现LeNet-5网络,与可视化网络
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
模型源自Yann LeCun(1998)的論文《Gradient-Based Learning Applied to Document Recognition》,用于MNIST數(shù)據(jù)集。模型輸入為32X32的灰度圖像,第一層為6個5X5卷積核,不擴展邊界;第二層為2X2的最大值池化層,步進為2X2;第三層為16個5X5卷積核,不擴展邊界;第四層為2X2的最大值池化層,步進為2X2;第五層為展平層,并全連接120個節(jié)點;第六層為全連接層,84個節(jié)點;第七層為全連接softmax層,輸出結(jié)果。
??????? 原論文中第二層池化層和第三層卷積層之間為是部分連接。本文中并未考慮,而是做成全連接,模型結(jié)構(gòu)如下圖所示。
?
??????? 模型采用keras的Sequential實現(xiàn),源數(shù)據(jù)分為train和test兩個文件夾,每個文件夾下有十個子文件夾,分別方有各數(shù)字對應(yīng)的灰度圖。實現(xiàn)代碼如下:
import os import cv2 from numpy import * from keras.models import Sequential from keras.layers import Dense from keras.layers import Conv2D, MaxPooling2D, Flatten from keras.optimizers import SGD from keras.utils import np_utils from keras.utils.vis_utils import plot_modeldef loadData(path):data = []labels = []for i in range(10):dir = './'+path+'/'+str(i)listImg = os.listdir(dir)for img in listImg:data.append([cv2.imread(dir+'/'+img, 0)])labels.append(i)print path, i, 'is read'return data, labelstrainData, trainLabels = loadData('train') testData, testLabels = loadData('test') trainLabels = np_utils.to_categorical(trainLabels, 10) testLabels = np_utils.to_categorical(testLabels, 10)model = Sequential() model.add(Conv2D(filters=6, kernel_size=(5,5), padding='valid', input_shape=(1,28,28), activation='tanh')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Conv2D(filters=16, kernel_size=(5,5), padding='valid', activation='tanh')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Flatten()) model.add(Dense(120, activation='tanh')) model.add(Dense(84, activation='tanh')) model.add(Dense(10, activation='softmax')) sgd = SGD(lr=0.05, decay=1e-6, momentum=0.9, nesterov=True) model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy']) model.fit(trainData, trainLabels, batch_size=500, epochs=20, verbose=1, shuffle=True)plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=False)
網(wǎng)絡(luò)結(jié)構(gòu)圖如下:
總結(jié)
以上是生活随笔為你收集整理的Keras实现LeNet-5网络,与可视化网络的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#SetWindowPos窗口置顶
- 下一篇: 分享:RethinkDB 1.3 发布,