[深度学习]keras中获取某一层上的feature map的方法

在深度学习中,如果我们想获得某一个层上的feature map,就像下面的图这样,怎么做呢?

我们的代码是使用keras写的VGG16网络,网络结构如图:

那么我们随便抽取一层的数据吧,就拿第四层的pooling以后的结果作为输出吧,参考上面的网络结构,得到的结果维度应该是[1,56,56,128]的尺度。怎么做呢?

首先通过keras构建模型:

model = VGG16(include_top=True, weights='imagenet')

然后设置输入和输出为:原始的输入和该层对应的输出,然后使用predict函数得到对应的结果

dense_result = Model(inputs=model.input,outputs=model.get_layer("block2_pool").output) 
dense_res = dense_result.predict(x)#使用predict得到该层结果

设置随机数(或者固定的数字)来获取某一层的结果

rand_layer = random.randint(10,128)
x_output = dense_res[0,:,:,rand_layer] #获取某一层的数据:因为原始数据维度是[1,x,x,depths]的,我们仅仅提取某一个depth对应的[x,x]维度的信息
# 获取最大值,然后对该层数据进行归一化之后投影到0-255之间
max = np.max(x_output)
print(max,"max value is :")
# 然后进行归一化操作
x_output =x_output.astype("float32") / max * 255
print(x_output.shape)

最后对该层的feature进行显示,我们使用Pillow库

# 把图像转换成image可以表示的方式进行显示
from PIL import Image as PILImage
x_output =PILImage.fromarray(np.asarray(x_output)) 
x_output1 = x_output.resize((400,400)) 
x_output1.show() 
print(np.asarray(x_output1))

结果如上图所示啦~

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值