在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))

结果如上图所示啦~

以上这篇在keras中获取某一层上的feature map实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。