TensorFlow-抽取模型某一层特征 keras输出中间层结果的2种方法

本文介绍如何使用TensorFlow和Keras从预训练模型中提取特定层的特征,适用于图像相似度计算等任务。通过命名关键层并利用sess.run()或函数模型API,可以高效地获取模型中间层的输出。

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

TensorFlow-抽取模型某一层特征   原文链接

深度学习具有强大的特征表达能力。有时候我们训练好分类模型,并不想用来进行分类,而是用来提取特征用于其他任务,比如相似图片计算。接下来讲下如何使用TensorFlow提取特征。

1.必须在模型中命名好要提取的那一层,如下

self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total], name='h_pool_flat')			

2.通过调用sess.run()来获取h_pool_flat层特征

feature = graph.get_operation_by_name("h_pool_flat").outputs[0]
batch_predictions, batch_feature = \
sess.run([predictions, feature], {input_x: x_test_batch, dropout_keep_prob: 1.0})

 

 keras输出中间层结果的2种方法  原文链接

1.使用函数模型API,新建一个model,将输入和输出定义为原来的model的输入和想要的那一层的输出,然后重新进行predict.

#coding=utf-8
import seaborn as sbn
import pylab as plt
import theano
from keras.models import Sequential
from keras.layers import Dense,Activation
 
 
from keras.models import Model
 
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(16, activation='relu',name="Dense_1"))
model.add(Dense(1, activation='sigmoid',name="Dense_2"))
model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])
 
# Generate dummy data
import numpy as np
#假设训练和测试使用同一组数据
data = np.random.random((1000, 100))
labels = np.random.randint(2, size=(1000, 1))
 
# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs=10, batch_size=32)
#已有的model在load权重过后
#取某一层的输出为输出新建为model,采用函数模型
dense1_layer_model = Model(inputs=model.input,
                                     outputs=model.get_layer('Dense_1').output)
#以这个model的预测值作为输出
dense1_output = dense1_layer_model.predict(data)
 
print dense1_output.shape
print dense1_output[0]

2.因为我的后端是使用的theano,所以还可以考虑使用theano的函数:

#这是一个theano的函数
dense1 = theano.function([model.layers[0].input],model.layers[1].output,allow_input_downcast=True)
dense1_output = dense1(data)  #visualize these images's FC-layer feature
print dense1_output[0]

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值