本篇文章給大家分享的是有關(guān)怎么使用Keras完成CNN模型搭建,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。
創(chuàng)新新互聯(lián),憑借10年的成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作經(jīng)驗(yàn),本著真心·誠(chéng)心服務(wù)的企業(yè)理念服務(wù)于成都中小企業(yè)設(shè)計(jì)網(wǎng)站有上1000+案例。做網(wǎng)站建設(shè),選創(chuàng)新互聯(lián)。
對(duì)于圖像分類(lèi)任務(wù)而言,卷積神經(jīng)網(wǎng)絡(luò)(CNN)是目前最優(yōu)的網(wǎng)絡(luò)結(jié)構(gòu),沒(méi)有之一。在面部識(shí)別、自動(dòng)駕駛、物體檢測(cè)等領(lǐng)域,CNN被廣泛使用,并都取得了最優(yōu)性能。對(duì)于絕大多數(shù)深度學(xué)習(xí)新手而言,數(shù)字手寫(xiě)體識(shí)別任務(wù)可能是第一個(gè)上手的項(xiàng)目,網(wǎng)絡(luò)上也充斥著各種各樣的成熟工具箱的相關(guān)代碼,新手在利用相關(guān)工具箱跑一遍程序后就能立刻得到很好的結(jié)果,這時(shí)候獲得的感受只有一個(gè)——深度學(xué)習(xí)真神奇,卻沒(méi)能真正了解整個(gè)算法的具體流程。小編將利用Keras和TensorFlow設(shè)計(jì)一個(gè)簡(jiǎn)單的二維卷積神經(jīng)網(wǎng)絡(luò)(CNN)模型,手把手教你用代碼完成MNIST數(shù)字識(shí)別任務(wù),便于理解深度學(xué)習(xí)的整個(gè)流程。
模型使用的MNIST數(shù)據(jù)集,該數(shù)據(jù)集是目前最大的數(shù)字手寫(xiě)體數(shù)據(jù)集(0~9),總共包含60,000張訓(xùn)練圖像和10,000張測(cè)試圖像,每張圖像的大小為28x28,灰度圖。第一步是加載數(shù)據(jù)集,可以通過(guò)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大小的手寫(xiě)體圖像,y_train表示訓(xùn)練圖像對(duì)應(yīng)的標(biāo)簽。同理,X_test表示測(cè)試數(shù)據(jù)集,總共10,000張28x28大小的手寫(xiě)體圖像,y_test表示測(cè)試圖像對(duì)應(yīng)的標(biāo)簽。下面對(duì)數(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
# 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)
對(duì)圖像信息進(jìn)行必要的處理之后,標(biāo)簽數(shù)據(jù)y_train和y_test被轉(zhuǎn)換為分類(lèi)格式(向量形式),即標(biāo)簽‘3’被轉(zhuǎn)換為向量[ 0,0,0,1,0,0,0,0,0,0]用于建模,標(biāo)簽向量非零的位置減一(從0開(kāi)始)后表示該圖像的具體標(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分類(lèi)器。如果你對(duì)每層的作用不熟悉的話,建議學(xué)習(xí)CS231課程。
在最大池化層和全連接層之后,模型中引入dropout作為正則化來(lái)減少過(guò)擬合問(wèn)題。
#導(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多分類(lèi)損失函數(shù)。由于所有的標(biāo)簽都具有相似的權(quán)重,因此將其作為性能指標(biāo),并使用AdaDelta梯度下降技術(shù)來(lái)優(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ù)對(duì)模型進(jìn)行訓(xùn)練,以便能夠識(shí)別手寫(xiě)數(shù)字。即使用X_train和y_train來(lái)擬合模型。
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表示對(duì)所有訓(xùn)練樣本進(jìn)行一個(gè)前向傳播過(guò)程和一個(gè)反向傳播過(guò)程,Batch_Size表示每次前向過(guò)程和反向過(guò)程時(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
可以看到,測(cè)試準(zhǔn)確性高達(dá)99%+,這也意味著該模型對(duì)于預(yù)測(cè)訓(xùn)練得很好。對(duì)整個(gè)過(guò)程訓(xùn)練和測(cè)試過(guò)程進(jìn)行可視化,即畫(huà)出訓(xùn)練和測(cè)試的準(zhǔn)確曲線與損失函數(shù)曲線,如下所示。從圖中可以看到,隨著訓(xùn)練迭代次數(shù)的增加,模型在訓(xùn)練和測(cè)試數(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)用場(chǎng)景中。
以上就是怎么使用Keras完成CNN模型搭建,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
文章名稱(chēng):怎么使用Keras完成CNN模型搭建
分享網(wǎng)址:http://jinyejixie.com/article16/ipejgg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、搜索引擎優(yōu)化、App設(shè)計(jì)、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站維護(hù)、關(guān)鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)