使用Keras構(gòu)造簡單的CNN網(wǎng)絡(luò)實例
1. 導(dǎo)入各種模塊
基本形式為:
import 模塊名
from 某個文件 import 某個模塊
2. 導(dǎo)入數(shù)據(jù)(以兩類分類問題為例,即numClass = 2)
訓(xùn)練集數(shù)據(jù)data
可以看到,data是一個四維的ndarray
訓(xùn)練集的標簽
3. 將導(dǎo)入的數(shù)據(jù)轉(zhuǎn)化我keras可以接受的數(shù)據(jù)格式
keras要求的label格式應(yīng)該為binary class matrices,所以,需要對輸入的label數(shù)據(jù)進行轉(zhuǎn)化,利用keras提高的to_categorical函數(shù)
label = np_utils.to_categorical(label, numClass
此時的label變?yōu)榱巳缦滦问?/p>
(注:PyCharm無法顯示那么多的數(shù)據(jù),所以下面才只顯示了1000個數(shù)據(jù),實際上該例子所示的數(shù)據(jù)集有1223個數(shù)據(jù))
4. 建立CNN模型
以下圖所示的CNN網(wǎng)絡(luò)為例
#生成一個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. 開始訓(xùn)練model
利用model.train_on_batch或者model.fit
補充知識:keras 多分類一些函數(shù)參數(shù)設(shè)置
用Lenet-5 識別Mnist數(shù)據(jù)集為例子:
采用下載好的Mnist數(shù)據(jù)壓縮包轉(zhuǎn)換成PNG圖片數(shù)據(jù)集,加載圖片采用keras圖像預(yù)處理模塊中的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
定義圖像數(shù)據(jù)信息及訓(xùn)練參數(shù)
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)
網(wǎng)絡(luò)模型定義
主要注意最后的輸出層定義
比如Mnist數(shù)據(jù)集是要對0~9這10種手寫字符進行分類,那么網(wǎng)絡(luò)的輸出層就應(yīng)該輸出一個10維的向量,10維向量的每一維代表該類別的預(yù)測概率,所以此處輸出層的定義為:
x = Dense(10,activation='softmax')(x)
此處因為是多分類問題,Dense()的第一個參數(shù)代表輸出層節(jié)點數(shù),要輸出10類則此項值為10,激活函數(shù)采用softmax,如果是二分類問題第一個參數(shù)可以是1,激活函數(shù)可選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傳入圖像數(shù)據(jù)集
注意用ImageDataGenerator的方法.flow_from_directory()加載圖片數(shù)據(jù)流時,參數(shù)class_mode要設(shè)為‘categorical',如果是二分類問題該值可設(shè)為‘binary',另外要設(shè)置classes參數(shù)為10種類別數(shù)字所在文件夾的名字,以列表的形式傳入。
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', #多分類問題設(shè)為'categorical' classes=['0','1','2','3','4','5','6','7','8','9'] #十種數(shù)字圖片所在文件夾的名字 ) validation_generator = test_datagen.flow_from_directory( validation_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='categorical' )
訓(xùn)練和保存模型及權(quán)值
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')
至此訓(xùn)練結(jié)束
圖片預(yù)測
注意model.save()可以將模型以及權(quán)值一起保存,而model.save_weights()只保存了網(wǎng)絡(luò)權(quán)值,此時如果要進行預(yù)測,必須定義有和訓(xùn)練出該權(quán)值所用的網(wǎng)絡(luò)結(jié)構(gòu)一模一樣的一個網(wǎng)絡(luò)。
此處利用keras.models中的load_model方法加載model.save()所保存的模型,以恢復(fù)網(wǎng)絡(luò)結(jié)構(gòu)和參數(shù)。
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.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構(gòu)造簡單的CNN網(wǎng)絡(luò)實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python循環(huán)接收http請求數(shù)據(jù)方式
這篇文章主要介紹了python循環(huán)接收http請求數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
PyTorch中torch.utils.data.DataLoader簡單介紹與使用方法
DataLoader是PyTorch中讀取數(shù)據(jù)的一個重要接口,基本上用PyTorch訓(xùn)練模型都會用到,下面這篇文章主要給大家介紹了關(guān)于PyTorch中torch.utils.data.DataLoader簡單介紹與使用方法的相關(guān)資料,需要的朋友可以參考下2022-06-06
Python:Scrapy框架中Item Pipeline組件使用詳解
這篇文章主要介紹了Python:Scrapy框架中Item Pipeline組件使用詳解,具有一定借鑒價值,需要的朋友可以參考下2017-12-12

