You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mask R-CNN推理时Lambda层输出形状推断失败问题求助

解决Mask R-CNN中Lambda层无法推断输出形状的问题

当运行Mask R-CNN示例代码的demo.ipynb,执行model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)时,触发如下错误:

NotImplementedError: Exception encountered when calling Lambda.call().
We could not automatically infer the shape of the Lambda's output. Please specify the `output_shape` argument for this Lambda layer.
Arguments received by Lambda.call():
• args=('<KerasTensor shape=(None, 1000, 1, 1, 1024), dtype=float32, sparse=False, name=keras_tensor_3553>',)
• kwargs={'mask': 'None'}

错误源于fpn_classifier_graph函数中的Lambda层,你之前尝试的修改未解决问题,核心原因是指定的output_shape与张量挤压后的实际维度不匹配。

正确修改方案

方案1:修正output_shape的维度索引

输入张量形状为(None, 1000, 1, 1, 1024),两次squeeze操作分别移除第2、3位索引的维度(Keras维度索引从0开始),最终保留的维度是(batch_size, proposals, channels),对应原形状的第0、1、4位索引。修改代码如下:

shared = KL.Lambda(lambda x: K.squeeze(K.squeeze(x, 3), 2),
                   name="pool_squeeze",
                   output_shape=lambda s: (s[0], s[1], s[4]))(x)

方案2:使用tf.squeeze指定轴(更适配新版本Keras/TensorFlow)

如果你的环境使用较新的TensorFlow/Keras版本,可以直接用tf.squeeze指定要移除的轴,无需手动声明output_shape,框架会自动推断形状:

import tensorflow as tf

shared = KL.Lambda(lambda x: tf.squeeze(x, axis=[2, 3]),
                   name="pool_squeeze")(x)

错误原因说明

你之前的修改中,output_shape写的是(s[0], s[1], s[3]),但原输入形状的第3位索引对应的值是1(被squeeze移除的维度),而实际需要保留的通道维度是第4位索引的1024,这导致形状推断逻辑错误,进而触发异常。

内容的提问来源于stack exchange,提问作者carwrxuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 07:18:13