利用預訓練模型可以有效的提取圖片的特徵,提取出特徵後,可以利用除了神經網絡以外的別的方法,對特徵數據集進行分析。顯然,如果我們擁有的數據集比較少的時候,不足以用數據集訓練一個龐大的神經網絡,但是可以利用提取特徵的方法,獲得特徵數據,再利用支持向量機等機器學習方法,或者PCA,PLS-DA等方法對數據集進行分析。
提取特徵不需要對預訓練好的模型進行fine-tuning,權重不需要改變,所以相對來說比較簡單。只是需要下載和導入模型。Keras 的應用模塊(keras.applications)提供了帶有預訓練權值的深度學習模型,這些模型可以用來進行預測、特徵提取和微調(fine-tuning)。keras中的接下來以利用VGG16為例子,進行特徵提取說明。
1. 提取feature的基本步驟
from keras.applications.vgg16 import VGG16from keras.preprocessing import imagefrom keras.applications.vgg16 import preprocess_input, decode_predictionsfrom keras.utils.vis_utils import plot_modelimport matplotlib.pyplot as plt# 初始化一個預訓練模型時,會自動下載權重到 ~/.keras/models/ 目錄下。weights='imagenet'表示運用模型預訓練的權重,include_top=False表示除去全連接層model = VGG16(weights='imagenet', include_top=False)
model.summary()
img_path = 'cat1.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
features = model.predict(x)
features.shape
「
(1, 7, 7, 512)
」
#把多維數組拉平成二維數組,這樣以後可以把每個圖片的特徵都存到一起,供後續分析使用
features.reshape(1,-1).shape
「
(1, 25088)
」
2. 提取任意一層輸出的基本步驟
from keras.applications.vgg16 import VGG16from keras.preprocessing import imagefrom keras.applications.vgg16 import preprocess_input, decode_predictionsfrom keras.utils.vis_utils import plot_modelimport matplotlib.pyplot as pltfrom keras.models import Model
base_model = VGG16(weights='imagenet', include_top=False)
#指定提取'block2_conv2'層的輸出。可以根據實際情況隨意改變
model = Model(inputs=base_model.input, outputs = base_model.get_layer('block2_conv2').output)
img_path = 'cat1.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
block2_conv2= model.predict(x)