Keras —— 遷移學習fine-tuning
阿新 • • 發佈:2019-01-03
該程式演示將一個預訓練好的模型在新資料集上重新fine-tuning的過程。我們凍結卷積層,只調整全連線層。
- 在MNIST資料集上使用前五個數字[0…4]訓練一個卷積網路。
- 在後五個數字[5…9]用卷積網路做分類,凍結卷積層並且微調全連線層
一、變數初始化
now = datetime.datetime.now
batch_size = 128
nb_classes = 5
nb_epoch = 5
# 輸入影象的維度
img_rows, img_cols = 28, 28
# 使用卷積濾波器的數量
nb_filters = 32
# 用於max pooling的pooling面積的大小
pool_size = 2
# 卷積核的尺度
kernel_size = (3,3)
input_shape = (img_rows, img_cols, 1)
# 資料,在訓練和測試資料集上混洗和拆分
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train_lt5 = X_train[y_train < 5]
y_train_lt5 = y_train[y_train < 5]
X_test_lt5 = X_test[y_test < 5]
y_test_lt5 = y_test[y_test < 5]
X_train_gte5 = X_train[y_train >= 5]
#使標籤從0~4,故-5
y_train_gte5 = y_train[y_train >= 5] - 5
X_test_gte5 = X_test[y_test >= 5]
y_test_gte5 = y_test[y_test >= 5] - 5
二、模型的訓練函式
def train_model(model, train, test, nb_classes):
#train[0]是圖片,train[1]是標籤
X_train = train[0].reshape((train[0].shape[0 ],) + input_shape)#1D+3D=4D
X_test = test[0].reshape((test[0].shape[0],) + input_shape)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
Y_train = np_utils.to_categorical(train[1], nb_classes)
Y_test = np_utils.to_categorical(test[1], nb_classes)
model.compile(loss='categorical_crossentropy',
optimizer='adadelta',
metrics=['accuracy'])
t = now()
model.fit(X_train, Y_train,
batch_size=batch_size, nb_epoch=nb_epoch,
verbose=1,
validation_data=(X_test, Y_test))
print('Training time: %s' % (now() - t))
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])
三、建立模型,構建卷積層(特徵層)和全連線層(分類層)
feature_layers = [
Convolution2D(nb_filters, kernel_size,
padding='valid',
input_shape=input_shape),
Activation('relu'),
Convolution2D(nb_filters, kernel_size),
Activation('relu'),
MaxPooling2D(pool_size=(pool_size, pool_size)),
Dropout(0.25),
Flatten(),
]
classification_layers = [
Dense(128),
Activation('relu'),
Dropout(0.5),
Dense(nb_classes),
Activation('softmax')
]
model = Sequential(feature_layers + classification_layers)
四、對模型進行預訓練
train_model(model,
(X_train_lt5, y_train_lt5),
(X_test_lt5, y_test_lt5), nb_classes)
五、凍結預訓練模型的特徵層
for l in feature_layers:
l.trainable = False
六、fine_tuning分類層
train_model(model,
(X_train_gte5, y_train_gte5),
(X_test_gte5, y_test_gte5), nb_classes)
原始碼地址: