今日練習內容為建構CNN模型來分類鳥類圖片,最後講解一些架構的演進
# Load Data & Prepare X, y
import cv2
import os
X_Raw_train = []
X_Raw_test = []
X_Raw_valid = []
y_Raw_train = []
y_Raw_test = []
y_Raw_valid = []
target_name = {}
parent_dir = './Birds/285 birds/'
for first_layer_dir in os.listdir(parent_dir):
layer01_dir = os.path.join(parent_dir, first_layer_dir)
if not os.path.isdir(layer01_dir):
continue
if first_layer_dir == 'image to test':
continue
if first_layer_dir == 'one image to test':
continue
for second_layer_dir in os.listdir(layer01_dir):
layer02_dir = os.path.join(layer01_dir, second_layer_dir)
if not os.path.isdir(layer02_dir):
continue
Label_index = os.listdir(layer01_dir).index(second_layer_dir)
if Label_index == 20:
break
for files in os.listdir(layer02_dir):
filename = os.path.join(layer02_dir, files)
if filename.endswith('.jpg'):
image = cv2.imread(filename)
if first_layer_dir == 'train':
X_Raw_train.append(image)
y_Raw_train.append(Label_index)
target_name[Label_index] = second_layer_dir
if first_layer_dir == 'test':
X_Raw_test.append(image)
y_Raw_test.append(Label_index)
target_name[Label_index] = second_layer_dir
if first_layer_dir == 'valid':
X_Raw_valid.append(image)
y_Raw_valid.append(Label_index)
target_name[Label_index] = second_layer_dir
# preprocessing X, y
import numpy as np
X_train = np.array(X_Raw_train).astype(np.float32)/255
X_test = np.array(X_Raw_test).astype(np.float32)/255
X_valid = np.array(X_Raw_valid).astype(np.float32)/255
y_train = np.array(y_Raw_train).astype(np.float32)
y_test = np.array(y_Raw_test).astype(np.float32)
y_valid = np.array(y_Raw_valid).astype(np.float32)
# Bulid Model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten
AlexNet_Model = Sequential()
AlexNet_Model.add(Conv2D(96,(11,11), strides = 4, activation = 'relu', input_shape=(224,224, 3)))
AlexNet_Model.add(MaxPooling2D((3,3), 2))
AlexNet_Model.add(Conv2D(32,(5,5), padding = 'same', activation = 'relu'))
AlexNet_Model.add(MaxPooling2D((3,3), 2))
AlexNet_Model.add(Conv2D(32,(3,3), padding = 'same', activation = 'relu'))
AlexNet_Model.add(Conv2D(32,(3,3), padding = 'same', activation = 'relu'))
AlexNet_Model.add(Conv2D(32,(3,3), padding = 'same', activation = 'relu'))
AlexNet_Model.add(MaxPooling2D((3,3), 2))
AlexNet_Model.add(Flatten())
AlexNet_Model.add(Dense(2048, activation = 'relu'))
AlexNet_Model.add(Dense(1024, activation = 'relu'))
AlexNet_Model.add(Dense(20, activation = 'softmax'))
# Train Model
AlexNet_Model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc'])
AlexNet_Model.history = Alex_Model.fit(X_train, y_train, epochs=30, batch_size=16, validation_data=(X_valid, y_valid))
附上AlexNet 的架構