网络编程
位置:首页>> 网络编程>> Python编程>> 在keras中获取某一层上的feature map实例

在keras中获取某一层上的feature map实例

作者:今天好好吃饭了吗  发布时间:2023-10-19 11:37:24 

标签:keras,feature,map

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

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

在keras中获取某一层上的feature map实例

那么我们随便抽取一层的数据吧,就拿第四层的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))

结果如上图所示啦~

来源:https://blog.csdn.net/qq_32376851/article/details/83718780

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com