您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)怎么使用Keras完成CNN模型搭建,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
對于圖像分類任務(wù)而言,卷積神經(jīng)網(wǎng)絡(luò)(CNN)是目前最優(yōu)的網(wǎng)絡(luò)結(jié)構(gòu),沒有之一。在面部識(shí)別、自動(dòng)駕駛、物體檢測等領(lǐng)域,CNN被廣泛使用,并都取得了最優(yōu)性能。對于絕大多數(shù)深度學(xué)習(xí)新手而言,數(shù)字手寫體識(shí)別任務(wù)可能是第一個(gè)上手的項(xiàng)目,網(wǎng)絡(luò)上也充斥著各種各樣的成熟工具箱的相關(guān)代碼,新手在利用相關(guān)工具箱跑一遍程序后就能立刻得到很好的結(jié)果,這時(shí)候獲得的感受只有一個(gè)——深度學(xué)習(xí)真神奇,卻沒能真正了解整個(gè)算法的具體流程。小編將利用Keras和TensorFlow設(shè)計(jì)一個(gè)簡單的二維卷積神經(jīng)網(wǎng)絡(luò)(CNN)模型,手把手教你用代碼完成MNIST數(shù)字識(shí)別任務(wù),便于理解深度學(xué)習(xí)的整個(gè)流程。
模型使用的MNIST數(shù)據(jù)集,該數(shù)據(jù)集是目前最大的數(shù)字手寫體數(shù)據(jù)集(0~9),總共包含60,000張訓(xùn)練圖像和10,000張測試圖像,每張圖像的大小為28x28,灰度圖。第一步是加載數(shù)據(jù)集,可以通過Keras API完成:
#源代碼不能直接下載,在這里進(jìn)行稍微修改,下載數(shù)據(jù)集后指定路徑#下載鏈接:https://pan.baidu.com/s/1jH6uFFC 密碼: dw3dfrom __future__ import print_functionimport kerasimport numpy as np path='./mnist.npz' f = np.load(path) X_train, y_train = f['x_train'], f['y_train'] X_test, y_test = f['x_test'], f['y_test']
上述代碼中,X_train表示訓(xùn)練數(shù)據(jù)集,總共60,000張28x28大小的手寫體圖像,y_train表示訓(xùn)練圖像對應(yīng)的標(biāo)簽。同理,X_test表示測試數(shù)據(jù)集,總共10,000張28x28大小的手寫體圖像,y_test表示測試圖像對應(yīng)的標(biāo)簽。下面對數(shù)據(jù)集部分?jǐn)?shù)據(jù)進(jìn)行可視化,以便更好地了解構(gòu)建的模型深度學(xué)習(xí)模型的目的。
import matplotlib.pyplot as plt fig = plt.figure()for i in range(9): plt.subplot(3,3,i+1) plt.tight_layout() plt.imshow(X_train[i], cmap='gray', interpolation='none') plt.title("Digit: {}".format(y_train[i])) plt.xticks([]) plt.yticks([]) fig從圖中可以看到,左上角是存儲(chǔ)在訓(xùn)練集X_train[0]的手寫體圖像‘5’,y_train[0]表示對應(yīng)的標(biāo)簽‘5’。整個(gè)深度學(xué)習(xí)模型的功能是訓(xùn)練好之后能夠預(yù)測出別人手寫的數(shù)字具體是什么。
# let's print the actual data shape before we reshape and normalizeprint("X_train shape", X_train.shape)print("y_train shape", y_train.shape)print("X_test shape", X_test.shape)print("y_test shape", y_test.shape)#input image size 28*28img_rows , img_cols = 28, 28#reshaping#"channels_first" assumes (channels, conv_dim1, conv_dim2, conv_dim3).X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1)#more reshapingX_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255print('X_train shape:', X_train.shape) #X_train shape: (60000, 28, 28, 1)
對圖像信息進(jìn)行必要的處理之后,標(biāo)簽數(shù)據(jù)y_train和y_test被轉(zhuǎn)換為分類格式(向量形式),即標(biāo)簽‘3’被轉(zhuǎn)換為向量[ 0,0,0,1,0,0,0,0,0,0]用于建模,標(biāo)簽向量非零的位置減一(從0開始)后表示該圖像的具體標(biāo)簽,即若圖像的標(biāo)簽向量在下標(biāo)5處不為0,則表示該圖像代表數(shù)字‘4’。
import keras#set number of categoriesnum_category = 10# convert class vectors to binary class matricesy_train = keras.utils.to_categorical(y_train, num_category) y_test = keras.utils.to_categorical(y_test, num_category)
在數(shù)據(jù)準(zhǔn)備好提供給模型后,需要定義模型的體系結(jié)構(gòu)并使用必要的優(yōu)化函數(shù),損失函數(shù)和性能指標(biāo)進(jìn)行編譯。
構(gòu)建模型遵循的體系結(jié)構(gòu)是經(jīng)典卷積神經(jīng)網(wǎng)絡(luò),分別含有2個(gè)卷積層,之后是連接全連接層和softmax分類器。如果你對每層的作用不熟悉的話,建議學(xué)習(xí)CS231課程。
在最大池化層和全連接層之后,模型中引入dropout作為正則化來減少過擬合問題。
#導(dǎo)入相關(guān)層的結(jié)構(gòu)from __future__ import print_functionimport kerasfrom keras.datasets import mnistfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2Dfrom keras import backend as kimport matplotlib.pyplot as pltimport numpy as np## model buildingmodel = Sequential()#convolutional layer with rectified linear unit activationmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))#32 convolution filters used each of size 3x3#againmodel.add(Conv2D(64, (3, 3), activation='relu'))#64 convolution filters used each of size 3x3#choose the best features via poolingmodel.add(MaxPooling2D(pool_size=(2, 2)))#randomly turn neurons on and off to improve convergencemodel.add(Dropout(0.25))#flatten since too many dimensions, we only want a classification outputmodel.add(Flatten())#fully connected to get all relevant datamodel.add(Dense(128, activation='relu'))#one more dropout for convergence' sake :) model.add(Dropout(0.5))#output a softmax to squash the matrix into output probabilitiesmodel.add(Dense(num_category, activation='softmax'))
模型搭建好之后,需要進(jìn)行編譯。在本文使用categorical_crossentropy多分類損失函數(shù)。由于所有的標(biāo)簽都具有相似的權(quán)重,因此將其作為性能指標(biāo),并使用AdaDelta梯度下降技術(shù)來優(yōu)化模型參數(shù)。
#Adaptive learning rate (adaDelta) is a popular form of gradient descent rivaled only by adam and adagrad#categorical ce since we have multiple classes (10) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])
在定義和編譯模型架構(gòu)之后,需要使用訓(xùn)練數(shù)據(jù)對模型進(jìn)行訓(xùn)練,以便能夠識(shí)別手寫數(shù)字。即使用X_train和y_train來擬合模型。
batch_size = 128 num_epoch = 10#model trainingmodel_log = model.fit(X_train, y_train, batch_size=batch_size, epochs=num_epoch, verbose=1, validation_data=(X_test, y_test))
Epoch表示對所有訓(xùn)練樣本進(jìn)行一個(gè)前向傳播過程和一個(gè)反向傳播過程,Batch_Size表示每次前向過程和反向過程時(shí)處理的訓(xùn)練樣本數(shù),訓(xùn)練輸出如下所示:
score = model.evaluate(X_test, y_test, verbose=0)print('Test loss:', score[0]) #Test loss: 0.0296396646054print('Test accuracy:', score[1]) #Test accuracy: 0.9904
可以看到,測試準(zhǔn)確性高達(dá)99%+,這也意味著該模型對于預(yù)測訓(xùn)練得很好。對整個(gè)過程訓(xùn)練和測試過程進(jìn)行可視化,即畫出訓(xùn)練和測試的準(zhǔn)確曲線與損失函數(shù)曲線,如下所示。從圖中可以看到,隨著訓(xùn)練迭代次數(shù)的增加,模型在訓(xùn)練和測試數(shù)據(jù)上的損失和準(zhǔn)確性趨于一致,模型最終趨于穩(wěn)定。
模型訓(xùn)練好后需要保存訓(xùn)練好的參數(shù),以便下次直接調(diào)用。模型的體系結(jié)構(gòu)或結(jié)構(gòu)將存儲(chǔ)在json文件中,權(quán)重將以hdf5文件格式存儲(chǔ)。
#Save the model# serialize model to JSONmodel_digit_json = model.to_json()with open("model_digit.json", "w") as json_file: json_file.write(model_digit_json)# serialize weights to HDF5model.save_weights("model_digit.h6") print("Saved model to disk")
因此,保存好的模型可以之后進(jìn)行重復(fù)使用或輕易地遷移到其他應(yīng)用場景中。
以上就是怎么使用Keras完成CNN模型搭建,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。