首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从resnet层遍历4D (None,x,y,z)激活张量的2D矩阵?

如何从resnet层遍历4D (None,x,y,z)激活张量的2D矩阵?
EN

Stack Overflow用户
提问于 2019-05-14 20:17:17
回答 1查看 161关注 0票数 0

我想循环遍历4D张量的2D矩阵,它是resnet层(激活图或特征图)的输出,以便在测试时对其进行一点修改

注意:我正在使用keras

我尝试使用不同的代码将张量转换为numpy数组,但得到了一些奇怪的错误

总而言之:我只需要对resnet层的激活张量应用一些修改,然后继续向前传递,以便“可能”获得一些准确性增强

EN

回答 1

Stack Overflow用户

发布于 2019-05-14 21:10:25

您可以使用keras.backend.function。由于您尚未提供模型结构,因此我将使用以下模型,其输出为4D张量。

代码语言:javascript
运行
复制
model = Sequential(
   [
      Conv2D(z, 3, input_shape=(x, y, 3), padding="same"),
   ]
);

print(model.output.shape) # None, x, y, z)

使用此模型,可以使用keras.backend.function函数获取特定位置的输出值。在您的例子中,您试图获取最后两个维度,因此您必须使用批量索引和宽度索引(假设channels_last数据格式)进行索引。

代码语言:javascript
运行
复制
def get_model_output_at(model, batch_index, width_index):
    output = model.output[batch_index][width_index]
    return keras.backend.function(model.input, output)

现在,您可以使用此函数通过特定的索引来获取2D张量。

代码语言:javascript
运行
复制
func = get_model_output_at(model, 0, 0) # To access the first row of the first image(batch 0 and row 0).
images = np.random.randn(10, x, y, z) # Random images
output = func(images)
print(output.shape)  # (y, z)

编辑

要遍历功能图,请使用以下函数

代码语言:javascript
运行
复制
def get_feature_map_at(model, index):
    output = model.output[:, :, :, index]
    return keras.backend.function(model.input, output)

现在,使用上面的函数,您可以遍历每个功能图。

代码语言:javascript
运行
复制
image = np.random.randn(1, 55, 55, 256) 
for i in range(model.output.shape[-1]):
     feature_map_i_function = get_feature_map_at(model, i)
     feature_map_i = feature_map_i_function(image).reshape(55, 55)

实际上,使用model.predict和循环遍历结果数组可以更好地完成上述任务。

代码语言:javascript
运行
复制
image = np.random.randn(1, 55, 55, 256) 
predicted_feature_map = model.predict(image)
for i in range(predicted_feature_map.shape[-1]):
    feature_map_i = predicted_feature_map[:, :, :, i].reshape(55,55)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56130281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档