一、簡介
本文旨在通過一些簡單的案例姻蚓,學(xué)習(xí)如何通過keras搭建CNN宋梧。從數(shù)據(jù)讀取,數(shù)據(jù)處理狰挡,神經(jīng)網(wǎng)絡(luò)搭建捂龄,模型訓(xùn)練等。本文也是參考其他博主的文章基礎(chǔ)上做了些小修改學(xué)習(xí)的加叁,感謝其他博主的分享倦沧。
具體的CNN的原理,以及keras的原理它匕,這里就不啰嗦了展融。最后會提供一些參考博客,供大家學(xué)習(xí)超凳。完整的代碼的github地址:traffic
二愈污、流程
1.數(shù)據(jù)處理
#!/usr/bin/env python
# encoding: utf-8
from keras.preprocessing.image import img_to_array#圖片轉(zhuǎn)為array
from keras.utils import to_categorical#相當(dāng)于one-hot
from imutils import paths
import cv2
import numpy as np
import random
import os
def load_data(path,norm_size,class_num):
data = []#數(shù)據(jù)x
label = []#標(biāo)簽y
image_paths = sorted(list(paths.list_images(path)))#imutils模塊中paths可以讀取所有文件路徑
random.seed(0)#保證每次數(shù)據(jù)順序一致
random.shuffle(image_paths)#將所有的文件路徑打亂
for each_path in image_paths:
image = cv2.imread(each_path)#讀取文件
image = cv2.resize(image,(norm_size,norm_size))#統(tǒng)一圖片尺寸
image = img_to_array(image)
data.append(image)
maker = int(each_path.split(os.path.sep)[-2])#sep切分文件目錄,標(biāo)簽類別為文件夾名稱的變化轮傍,從0-61.如train文件下00014,label=14
label.append(maker)
data = np.array(data,dtype="float")/255.0#歸一化
label = np.array(label)
label = to_categorical(label,num_classes=class_num)#one-hot
return data,label
上面是數(shù)據(jù)目錄首装,下面是對應(yīng)的數(shù)據(jù)處理代碼创夜。主要分為幾個部分:
- 利用imutils模塊的paths將train或test中的所有圖片文件的路徑找出來image_paths。
- 對其中每張圖片仙逻,做如下操作驰吓,利用cv2讀取圖片和修改圖片尺寸(圖片尺寸不一,要統(tǒng)一尺寸)系奉。
- 依次將圖片和對應(yīng)的標(biāo)簽檬贰,保存到對應(yīng)的列表中
- 圖片進行歸一化操作,標(biāo)簽進行one-hot
2.神經(jīng)網(wǎng)絡(luò)搭建
這里搭建的網(wǎng)絡(luò)是經(jīng)典的LeNet網(wǎng)絡(luò)缺亮,從input>conv>pool>conv>pool>Dense>Dense(softmax)翁涤。具體LeNet的學(xué)習(xí),請見參考。這里是利用keras搭建的LeNet葵礼,keras的順序模型(另外一種為函數(shù)式API)号阿。
#!/usr/bin/env python
# encoding: utf-8
import keras
from keras.layers import Conv2D, MaxPooling2D, Dropout, Dense, Flatten
from keras.models import Sequential
import keras.backend as K
class Lenet:#經(jīng)典網(wǎng)絡(luò),不懂去查
def neural(channel,height,width,classes):
input_shape = (channel,height,width)
if K.image_data_format() == "channels_last":#確認(rèn)輸入維度,就是channel是在開頭鸳粉,還是結(jié)尾
input_shape = (height,width,channel)
model = Sequential()#順序模型(keras中包括順序模型和函數(shù)式API兩種方式)
model.add(Conv2D(20,(5,5),padding="same",activation="relu",input_shape=input_shape,name="conv1"))
model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),name="pool1"))
model.add(Conv2D(50,(5,5),padding="same",activation="relu",name="conv2",))
model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),name="pool2"))
model.add(Flatten())
model.add(Dense(500,activation="relu",name="fc1"))
model.add(Dense(classes,activation="softmax",name="fc2"))
return model
具體參數(shù)扔涧,其中卷積層卷積核一般不超過5,步長一般為1届谈。池化層一般大小和步長都為2枯夜。
3.訓(xùn)練
#!/usr/bin/env python
# encoding: utf-8
import matplotlib.pylab as plt
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import sys
sys.path.append("../process")#添加其他文件夾
import data_input#導(dǎo)入其他模塊
from traffic_network import Lenet
def train(aug, model,train_x,train_y,test_x,test_y):
model.compile(loss="categorical_crossentropy",
optimizer="Adam",metrics=["accuracy"])#配置
#model.fit(train_x,train_y,batch_size,epochs,validation_data=(test_x,test_y))
_history = model.fit_generator(aug.flow(train_x,train_y,batch_size=batch_size),
validation_data=(test_x,test_y),steps_per_epoch=len(train_x)//batch_size,
epochs=epochs,verbose=1)
#擬合,具體fit_generator請查閱其他文檔,steps_per_epoch是每次迭代艰山,需要迭代多少個batch_size湖雹,validation_data為test數(shù)據(jù),直接做驗證程剥,不參與訓(xùn)練
plt.style.use("ggplot")#matplotlib的美化樣式
plt.figure()
N = epochs
plt.plot(np.arange(0,N),_history.history["loss"],label ="train_loss")#model的history有四個屬性劝枣,loss,val_loss,acc,val_acc
plt.plot(np.arange(0,N),_history.history["val_loss"],label="val_loss")
plt.plot(np.arange(0,N),_history.history["acc"],label="train_acc")
plt.plot(np.arange(0,N),_history.history["val_acc"],label="val_acc")
plt.title("loss and accuracy")
plt.xlabel("epoch")
plt.ylabel("loss/acc")
plt.legend(loc="best")
plt.savefig("../result/result.png")
plt.show()
if __name__ =="__main__":
channel = 3
height = 32
width = 32
class_num = 62
norm_size = 32#參數(shù)
batch_size = 32
epochs = 40
model = Lenet.neural(channel=channel, height=height,
width=width, classes=class_num)#網(wǎng)絡(luò)
train_x, train_y = data_input.load_data("../data/train", norm_size, class_num)
test_x, test_y = data_input.load_data("../data/test", norm_size, class_num)#生成數(shù)據(jù)
aug = ImageDataGenerator(rotation_range=30,width_shift_range=0.1,
height_shift_range=0.1,shear_range=0.2,zoom_range=0.2,
horizontal_flip=True,fill_mode="nearest")#數(shù)據(jù)增強,生成迭代器
train(aug,model,train_x,train_y,test_x,test_y)#訓(xùn)練
這部分就是網(wǎng)絡(luò)的訓(xùn)練了织鲸,主要注意keras中model輸出的事history舔腾,有四個屬性可以查看。另外就是ImageDataGenerator數(shù)據(jù)增強搂擦,具體請查閱其他問下稳诚。
準(zhǔn)確率在94%,跟原博客預(yù)測準(zhǔn)確率一樣瀑踢。
三扳还、參考
代碼的github地址:traffic
原博客文章:
【Keras】從兩個實際任務(wù)掌握圖像分類
先附上一些講解比較好的CNN文章:
零基礎(chǔ)入門深度學(xué)習(xí)(4) - 卷積神經(jīng)網(wǎng)絡(luò)
keras中文文檔這里面內(nèi)容非常好,關(guān)于sequence,utils,fit_generator,ImageDataGenerator等等內(nèi)容都有橱夭,推薦瀏覽氨距。
從神經(jīng)網(wǎng)絡(luò)到卷積神經(jīng)網(wǎng)絡(luò)(CNN)
在Kaggle貓狗大戰(zhàn)沖到Top2%
imutols.path.list_image