Sách Deep Learning cơ bản
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
11.1 Transfer learning 157
# Load model VGG 16 của ImageNet dataset, include_top=False để bỏ phần Fully connected lay
baseModel = VGG16(weights='imagenet', include_top=False, \
input_tensor=Input(shape=(224, 224, 3)))
# Xây thêm các layer
# Lấy output của ConvNet trong VGG16
fcHead = baseModel.output
# Flatten trước khi dùng FCs
fcHead = Flatten(name='flatten')(fcHead)
# Thêm FC
fcHead = Dense(256, activation='relu')(fcHead)
fcHead = Dropout(0.5)(fcHead)
# Output layer với softmax activation
fcHead = Dense(17, activation='softmax')(fcHead)
# Xây dựng model bằng việc nối ConvNet của VGG16 và fcHead
model = model = Model(inputs=baseModel.input, outputs=fcHead)
# Chia traing set, test set tỉ lệ 80-20
X_train, X_test, y_train, y_test = train_test_split(list_image, labels, \
test_size=0.2, random_state=42)
# augmentation cho training data
aug_train = ImageDataGenerator(rescale=1./255, 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')
# augementation cho test
aug_test= ImageDataGenerator(rescale=1./255)
# freeze VGG model
for layer in baseModel.layers:
layer.trainable = False
opt = RMSprop(0.001)
model.compile(opt, 'categorical_crossentropy', ['accuracy'])
numOfEpoch = 25
H = model.fit_generator(aug_train.flow(X_train, y_train, batch_size=32),
steps_per_epoch=len(X_train)//32,
validation_data=(aug_test.flow(X_test, y_test, batch_size=32)),
validation_steps=len(X_test)//32,
epochs=numOfEpoch)
# unfreeze some last CNN layer:
for layer in baseModel.layers[15:]:
layer.trainable = True