我想循环遍历4D张量的2D矩阵,它是resnet层(激活图或特征图)的输出,以便在测试时对其进行一点修改
注意:我正在使用keras
我尝试使用不同的代码将张量转换为numpy数组,但得到了一些奇怪的错误
总而言之:我只需要对resnet层的激活张量应用一些修改,然后继续向前传递,以便“可能”获得一些准确性增强
发布于 2019-05-14 21:10:25
您可以使用keras.backend.function。由于您尚未提供模型结构,因此我将使用以下模型,其输出为4D张量。
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数据格式)进行索引。
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张量。
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)编辑
要遍历功能图,请使用以下函数
def get_feature_map_at(model, index):
output = model.output[:, :, :, index]
return keras.backend.function(model.input, output)现在,使用上面的函数,您可以遍历每个功能图。
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和循环遍历结果数组可以更好地完成上述任务。
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)https://stackoverflow.com/questions/56130281
复制相似问题