赞
踩
首先看看keras官网的代码:
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='predictions')(x)
此时我们可以考虑利用这种方式:(例子仍旧是keras官网的,不过以vgg19为例子。)
from keras.applications.vgg19 import VGG19 from keras.preprocessing import image from keras.applications.vgg19 import preprocess_input from keras.models import Model import numpy as np base_model = VGG19(weights='imagenet') model = Model(inputs=base_model.input, outputs=base_model.get_layer('block4_pool').output) 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) block4_pool_features = model.predict(x)
即这行代码:
model=Model(inputs=base_model.input,outputs=base_model.get_layer(‘block4_pool’).output)
这样我们就可以提取到某一层,(在vgg16中级即fc2);
全代码如下:
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
from keras.models import Model
import numpy as np
base_model = VGG16(weights='imagenet')
#查看VGG16源码,inculde_top是全连接层进行分类。但是我们需要提取到全连接层的4096输出,是fc2层
model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc2').output)
img_path = '1.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)
eg:在第一次加载预训练好的代码,会下载一些h5文件,但是会非常慢。(可以按照提示网站去下载,也很慢。)下载好之后放在C:\Users\自己用户.keras\models目录下
链接:https://pan.baidu.com/s/1HFRMd60CiivRVeCrt_58Yw
提取码:b89o
复制这段内容后打开百度网盘手机App,操作更方便哦
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。