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

如何确定Caffe Blob输入维度?实现网络层输入输出形状打印

获取Caffe网络每层的输入输出形状(无需直接查询父层输出)

我帮你整理了一个实用的方案,能输出你想要的格式的网络诊断信息,不用手动去查询父层的输出结果:

实现代码

# 假设self.net是已经完成初始化的Caffe Net实例
# 先打印对齐的表头
print(f"{'layer_number':<12} {'layer_name':<10} {'input_shape':<20} {'output_shape':<20}")
print("-" * 65)

# 遍历网络的每一层
for layer_idx, layer in enumerate(self.net.layers):
    # 获取当前层的名称
    layer_name = self.net._layer_names[layer_idx]
    
    # 获取输入形状:优先用层自身定义的input_shape,避免依赖父层
    if layer.input_shape and len(layer.input_shape) > 0:
        input_shape = tuple(layer.input_shape[0])
    else:
        # 对于无显式input_shape的中间层,自动关联输入Blob获取形状
        bottom_blob = self.net.bottom_names[layer_name][0]
        input_shape = self.net.blobs[bottom_blob].data.shape
    
    # 获取输出形状:通过层的输出Blob读取形状
    top_blob = self.net.top_names[layer_name][0]
    output_shape = self.net.blobs[top_blob].data.shape
    
    # 按格式打印信息
    print(f"{layer_idx:<12} {layer_name:<10} {str(input_shape):<20} {str(output_shape):<20}")

代码说明

  1. 排版优化:用f-string做了左对齐处理,保证输出的表格格式整洁易读
  2. 输入形状获取逻辑:
    • 优先读取层自身的input_shape属性,这是网络定义时的原生输入形状,完全不需要依赖父层数据
    • 对于卷积、池化这类没有显式定义input_shape的中间层,自动通过bottom_names关联到该层的输入Blob,直接读取其形状(全程自动关联,不需要你手动查找父层)
  3. 输出形状获取:通过top_names找到当前层的输出Blob,读取已有的data.shape即可
  4. 扩展性:如果遇到多输入的层(比如Concat、Eltwise),可以修改代码把所有输入形状都打印出来,这里默认取第一个输入形状做示例

示例输出(对应你的VGG16网络)

layer_number  layer_name  input_shape           output_shape          
-----------------------------------------------------------------
0             data        (10, 3, 224, 224)     (10, 3, 224, 224)     
1             conv1_1     (10, 3, 224, 224)     (10, 64, 224, 224)    
2             conv1_2     (10, 64, 224, 224)    (10, 64, 224, 224)    
3             pool1       (10, 64, 224, 224)    (10, 64, 112, 112)    
...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:08:52