首页 > 解决方案 > 我正在尝试手动实现 tf.nn.conv2d。对于深度 > 12,我得到不同的结果?

问题描述

Tensorflow 有一种专门的方法来卷积具有深度的图像(或多个具有不同过滤器的卷积图像堆叠在一起)。我试图根据它的功能文档来实现它。对于深度 <= 12,我的实现给出了 tensorflow 的精确结果,但对于更大的深度,我在精度范围内得到相同的结果,但它们并不完全相等。

depth = 1
image = tf.convert_to_tensor(np.random.rand(1, 14, 14, depth))
kernel = tf.convert_to_tensor(np.random.rand(5, 5, depth, 64))

image_padded = np.zeros([1, 18, 18, depth])
image_padded[:, 2:-2, 2:-2, :] = image
image_reshaped = np.zeros([1, 14, 14, 5*5*depth])
for i in range(14):
    for j in range(14):
        image_reshaped[:, i, j, :] = tf.reshape(image_padded[:, i:i+5, j:j+5, :], [-1])

kernel_reshaped = tf.reshape(kernel, [5*5*depth, 64])

man_conv = tf.matmul(image_reshaped, kernel_reshaped)
tf_conv = tf.nn.conv2d(image, kernel, strides=[1, 1, 1, 1], padding='SAME')

(tf.equal(man_conv, tf_conv).numpy()).all() # outputs true for depth <= 12

文档参考:

给定一个 shape 的输入张量 batch_shape + [in_height, in_width, in_channels]和一个 shape 的滤波器/内核张量[filter_height, filter_width, in_channels, out_channels],此操作执行以下操作:

  1. 将滤波器展平为形状为 的二维矩阵 [filter_height * filter_width * in_channels, output_channels]
  2. 从输入张量中提取图像块以形成 shape的虚拟[batch, out_height, out_width, filter_height * filter_width * in_channels]张量。
  3. 对于每个补丁,右乘滤波器矩阵和图像补丁向量。

标签: tensorflowconv-neural-networktensorflow2.0convolution

解决方案


推荐阅读