Keras_利用VGG16提取图片特征

本文介绍如何利用Keras库中的VGG16模型提取特定层的特征,特别是如何获取全连接层fc2的输出特征。通过修改模型结构,我们可以跳过顶层分类部分,直接获得中间层的特征表示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先看看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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值