1. 程式人生 > 程式設計 >使用Keras構造簡單的CNN網路例項

使用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,border_mode='valid',input_shape=data.shape[-3:]))
model.add(Activation('tanh'))#tanh
 
# layer2-conv2
model.add(Convolution2D(32,border_mode='valid'))
model.add(Activation('tanh'))#tanh
 
# layer3-conv3
model.add(Convolution2D(32,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,activation='relu',border_mode='same')(img_input)
x=MaxPooling2D((2,2),strides=(2,border_mode='same')(x)

x=Convolution2D(32,border_mode='same')(x)
x=MaxPooling2D((2,border_mode='same')(x)

x=Convolution2D(64,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,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.h5')
model.save('Mnist123model.h5')

至此訓練結束

圖片預測

注意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','9']
model=load_model('Mnist123model.h5')
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網路例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。