首先看看keras官网的代码:
使用 VGG16 提取特征
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np
model = VGG16(weights='imagenet', include_top=False)
img_path = 'elephant.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)
我们需要注意到它调用vgg16时,参数有一个include_top=False,此时我们再去看看vgg16源码如下:(keras.applications/vgg16.py代码),但这就有问题,因为如果include_top,得到的是卷积结束后的特征(当然不排除其他项目只需要到卷积层,这种可以直接拿keras官网代码。)但是我们想要得到全连接层的输出。则需要修改。
省略卷积层
if include_top:
# Classification block
x = layers.Flatten(name='flatten')(x)
x = layers.Dense(4096, activation='relu', name='fc1')(x)
x = layers.Dense(4096, activation='relu', name='fc2')(x)
x = layers.Dense(classes, activation='softmax', name='pred