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

tf.nn.conv2d_transpose报InvalidArgumentError:输入与滤波器深度需一致

解决tf.nn.conv2d_transpose的"input and filter must have the same depth"错误

你遇到的问题核心有两个关键点,其中最直接的错误是output_shape参数的最后一维设置错误,我们先拆解分析:

错误原因解析

  1. output_shape与卷积核输出通道不匹配
    你明确期望输出形状是(2,7,7,3),但代码里却写了(2,7,7,1)。在tf.nn.conv2d_transpose的规则里,output_shape的最后一维(输出通道数)必须和卷积核的第三个维度(out_channels)完全一致——你的卷积核ker第三个维度是3(对应3个输出通道),但output_shape最后一维是1,这直接触发了内部维度校验失败。

  2. 卷积核维度的正确性确认
    你对卷积核ker的形状定义是正确的,(5,5,3,1)完全符合tf.nn.conv2d_transpose的要求:

    • 前两维:卷积核的高和宽(kH, kW)
    • 第三维:输出通道数out_channels(你需要的3个通道)
    • 第四维:输入通道数in_channels(和输入inp最后一维的1完全匹配)
      这部分你没出错,输入和卷积核的深度确实都是1,不是问题根源。

修正后的代码

把output_shape改成你期望的(2,7,7,3)即可,完整修正代码如下:

import tensorflow as tf
import numpy as np
# Shape (2, 3, 3, 1) == (batch_sz, height, width, channels)
inp = tf.Variable(np.array(
    [
        [ [[1], [2], [3]], [[2], [3], [4]], [[7], [8], [9]] ],
        [ [[3], [2], [1]], [[2], [7], [2]], [[3], [2], [0]] ]
    ], dtype = np.float32
))
# Shape (5, 5, 3, 1) == (kH, kW, out_channels, in_channels)
ker = tf.Variable(np.array(
    [
        [[[1],[2],[1]], [[2],[2],[2]], [[1],[2],[1]], [[2],[1],[1]], [[1],[1],[1]]],
        [[[1],[2],[1]], [[2],[2],[2]], [[1],[2],[1]], [[2],[1],[1]], [[1],[1],[1]]],
        [[[1],[2],[1]], [[2],[2],[2]], [[1],[2],[1]], [[2],[1],[1]], [[1],[1],[1]]],
        [[[1],[2],[1]], [[2],[2],[2]], [[1],[2],[1]], [[2],[1],[1]], [[1],[1],[1]]],
        [[[1],[2],[1]], [[2],[2],[2]], [[1],[2],[1]], [[2],[1],[1]], [[1],[1],[1]]]
    ], dtype = np.float32
))
# 修正output_shape为期望的(2,7,7,3)
out = tf.nn.conv2d_transpose(inp, ker, (2, 7, 7, 3), (1, 1, 1, 1), padding='SAME', data_format='NHWC', name='conv_transpose')
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    output, kernel, input = sess.run([out, ker, inp])
# 验证输出形状
print(output.shape)  # 会输出(2,7,7,3),完全符合你的期望

额外说明

转置卷积的空间尺寸计算(padding='SAME'、strides=(1,1)场景):
输入尺寸是3x3,卷积核5x5,步长1,输出尺寸 = 输入尺寸 + 卷积核尺寸 - 1 = 3+5-1=7,所以7x7的空间维度是正确的,和你预期一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:07:55