這篇文章將為大家詳細講解有關用Keras如何構造簡單的CNN網絡,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
1. 導入各種模塊
基本形式為:
import 模塊名
from 某個文件 import 某個模塊
2. 導入數據(以兩類分類問題為例,即numClass = 2)
訓練集數據data
可以看到,data是一個四維的ndarray
訓練集的標簽
3. 將導入的數據轉化我keras可以接受的數據格式
keras要求的label格式應該為binary class matrices,所以,需要對輸入的label數據進行轉化,利用keras提高的to_categorical函數
label = np_utils.to_categorical(label, numClass
此時的label變為了如下形式
(注:PyCharm無法顯示那么多的數據,所以下面才只顯示了1000個數據,實際上該例子所示的數據集有1223個數據)
4. 建立CNN模型
以下圖所示的CNN網絡為例
#生成一個model model = Sequential() #layer1-conv1 model.add(Convolution2D(16, 3, 3, border_mode='valid',input_shape=data.shape[-3:])) model.add(Activation('tanh'))#tanh # layer2-conv2 model.add(Convolution2D(32, 3, 3, border_mode='valid')) model.add(Activation('tanh'))#tanh # layer3-conv3 model.add(Convolution2D(32, 3, 3, border_mode='valid')) model.add(Activation('tanh'))#tanh # layer4 model.add(Flatten()) model.add(Dense(128, init='normal')) model.add(Activation('tanh'))#tanh # layer5-fully connect model.add(Dense(numClass, init='normal')) model.add(Activation('softmax')) # sgd = SGD(l2=0.1,lr=0.001, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer=sgd,class_mode="categorical")
5. 開始訓練model
利用model.train_on_batch或者model.fit
補充知識:keras 多分類一些函數參數設置
用Lenet-5 識別Mnist數據集為例子:
采用下載好的Mnist數據壓縮包轉換成PNG圖片數據集,加載圖片采用keras圖像預處理模塊中的ImageDataGenerator。
首先import所需要的模塊
from keras.preprocessing.image import ImageDataGenerator from keras.models import Model from keras.layers import MaxPooling2D,Input,Convolution2D from keras.layers import Dropout, Flatten, Dense from keras import backend as K
定義圖像數據信息及訓練參數
img_width, img_height = 28, 28 train_data_dir = 'dataMnist/train' #train data directory validation_data_dir = 'dataMnist/validation'# validation data directory nb_train_samples = 60000 nb_validation_samples = 10000 epochs = 50 batch_size = 32
判斷使用的后臺
if K.image_dim_ordering() == 'th': input_shape = (3, img_width, img_height) else: input_shape = (img_width, img_height, 3)
網絡模型定義
主要注意最后的輸出層定義
比如Mnist數據集是要對0~9這10種手寫字符進行分類,那么網絡的輸出層就應該輸出一個10維的向量,10維向量的每一維代表該類別的預測概率,所以此處輸出層的定義為:
x = Dense(10,activation='softmax')(x)
此處因為是多分類問題,Dense()的第一個參數代表輸出層節點數,要輸出10類則此項值為10,激活函數采用softmax,如果是二分類問題第一個參數可以是1,激活函數可選sigmoid
img_input=Input(shape=input_shape) x=Convolution2D(32, 3, 3, activation='relu', border_mode='same')(img_input) x=MaxPooling2D((2,2),strides=(2, 2),border_mode='same')(x) x=Convolution2D(32,3,3,activation='relu',border_mode='same')(x) x=MaxPooling2D((2,2),strides=(2, 2),border_mode='same')(x) x=Convolution2D(64,3,3,activation='relu',border_mode='same')(x) x=MaxPooling2D((2,2),strides=(2, 2),border_mode='same')(x) x = Flatten(name='flatten')(x) x = Dense(64, activation='relu')(x) x= Dropout(0.5)(x) x = Dense(10,activation='softmax')(x) model=Model(img_input,x) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.summary()
利用ImageDataGenerator傳入圖像數據集
注意用ImageDataGenerator的方法.flow_from_directory()加載圖片數據流時,參數class_mode要設為‘categorical',如果是二分類問題該值可設為‘binary',另外要設置classes參數為10種類別數字所在文件夾的名字,以列表的形式傳入。
train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) # this is the augmentation configuration we will use for testing: # only rescaling test_datagen = ImageDataGenerator(rescale=1. / 255) train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical', #多分類問題設為'categorical' classes=['0','1','2','3','4','5','6','7','8','9'] #十種數字圖片所在文件夾的名字 ) validation_generator = test_datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical' )
訓練和保存模型及權值
model.fit_generator( train_generator, samples_per_epoch=nb_train_samples, nb_epoch=epochs, validation_data=validation_generator, nb_val_samples=nb_validation_samples ) model.save_weights('Mnist123weight.h6') model.save('Mnist123model.h6')
至此訓練結束
圖片預測
注意model.save()可以將模型以及權值一起保存,而model.save_weights()只保存了網絡權值,此時如果要進行預測,必須定義有和訓練出該權值所用的網絡結構一模一樣的一個網絡。
此處利用keras.models中的load_model方法加載model.save()所保存的模型,以恢復網絡結構和參數。
from keras.models import load_model from keras.preprocessing.image import img_to_array, load_img import numpy as np classes=['0','1','2','3','4','5','6','7','8','9'] model=load_model('Mnist123model.h6') while True: img_addr=input('Please input your image address:') if img_addr=="exit": break else: img = load_img(img_addr, False, target_size=(28, 28)) x = img_to_array(img) / 255.0 x = np.expand_dims(x, axis=0) result = model.predict(x) ind=np.argmax(result,1) print('this is a ', classes[ind])
關于用Keras如何構造簡單的CNN網絡就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。