[魔法陣系列] Convolutional Neural Network(CNN)之術式解析 中提到 CNN 由下列所組成:
本文應用這些概念,透過 Keras 實作 CNN 模型。用 Keras 的原因是因為它是高度抽象的深度學習框架,簡單易用,直觀的程式也能幫助各位見習魔法使理解。
input_shape
讓輸入的影像有一致的格式,程式中的 3 是指 R/B/G 三個通道activation function
設定為 ReLU (註:在[魔法陣系列] 王者誕生:AlexNet 之術式解析有介紹過 ReLU 的優點。)max pooling
,作用是降躁跟減少運算資源,設為 2 * 2 尺寸# Import Keras libraries and packages
from keras.models import Sequential #用來啟動 NN
from keras.layers import Conv2D # Convolution Operation
from keras.layers import MaxPooling2D # Pooling
from keras.layers import Flatten
from keras.layers import Dense # Fully Connected Networks
# initializing CNN
model = Sequential()
model.add(Conv2D(32, 3, 3, input_shape = (128, 128, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
同理,搭建第二層與第三層的 Convolutional Layer:
# Second convolutional layer
model.add(Conv2D(32, 3, 3, activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
# Third convolutional layer
model.add(Conv2D(64, 3, 3, activation = 'relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
謎之暴風龍:參數的設定依據不同的任務而調整,提醒大家在 NN 的參數調校中,沒有一個完美的參數配置。
model.add(Dense(output_dim = 128, activation = 'relu'))
model.add(Dense(output_dim = 1, activation = 'sigmoid'))
adam
(註:[精進魔法] Optimization:優化深度學習模型的技巧(中)提到 Adam 是實務上常用的方法。)binary_crossentropy
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('dataset/training_set', target_size = (128, 128), batch_size = 32, class_mode = 'binary')
test_set = test_datagen.flow_from_directory('dataset/test_set', target_size = (128, 128), batch_size = 32, class_mode = 'binary')
model.fit_generator(training_set, samples_per_epoch = 400, nb_epoch = 30, validation_data = test_set, nb_val_samples = 100)
import numpy as np
from keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (128, 128))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = model.predict(test_image)
training_set.class_indices
if result[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'
好了,今天就到這邊為止,這是一個滿陽春的 CNN 架構,參數也不是最佳配置,主要是用來複習 CNN 的概念以及能用 Keras 實作,希望大家練功時能觸類旁通,最後用暴風龍維爾德拉來祝福大家。
《關於我轉生變成史萊姆這檔事》中的暴風龍維爾德拉。圖片來源:https://www.sohu.com/a/258522569_100207985?spm=smmt.mt-acg.fd-d.17.1540252800023WRl5Apr