首页 > 解决方案 > Keras:替换模型的输入层不会更新 model.summary 中其他层的输出形状等

问题描述

我正在使用带有 TensorFlow 后端的 Keras。我想使用预训练的 U-Net 模型并用另一个替换输入层。我在大小 (256,256) 的图像上训练模型。当我预测更大的场景时,我想操纵输入,以便 UNet 完成它所做的事情,只是在另一个图像大小上,这样我就不必修饰图像或任何东西。这是我的代码:

model = load(model_path)
model.layers.pop(0)
new_input = Input(shape = (512,512))
model = Model(new_input,model(new_input_layer))

现在当我使用

print(model.summary())

它输出

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 512, 512, 3)     0
_________________________________________________________________
model_1 (Model)              multiple                  211825
=================================================================

如果我在做

model.layers[1].summary()

我明白了

____________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connectedto
=========================================================================
conv2d_1 (Conv2D)             (None, 256, 256, 16)    1216     input_1[0][0]
__________________________________________________________________________
batch_normalization_1       (None, 256, 256, 16)      64      conv2d_1[0][0]

等等。通常conv_2d_1的输出形状应该是 (None,512,512,16),但它没有正确更新(对于其他层也是如此)。此外,当我使用

model.layers[1].layers[0].output_shape

我得到与摘要中相同的结果。

当我使用调整后的模型进行预测时,所有输出都可以正常工作。但是,如果图像大小大于(512,512),例如(4096,4096),我会遇到与 gpu 有关的内存问题/分配问题。因此,我想计算所需的内存,预测图像并剪切它,如果它太大的话。但是要编写一个为我执行此操作的函数,我需要有关输出形状的正确信息。
有没有人有什么建议?也许我应该以另一种方式替换输入层?!也许我可以以某种方式更新模型?或者是否已经存在一些计算所需内存的keras函数?(我没有找到)感谢您的关注!:)

标签: pythontensorflowkeras

解决方案


There is a better alternative to what you are trying to achieve. The CNN layers can handle arbitrary shape if you specify shape=(None,None,3) says some height and width with 3 channels. You can train the original model like that and don't have to adjust tensor / image shapes when you predict.


推荐阅读