【问题标题】:Tensorflow convolution张量流卷积
【发布时间】:2018-03-14 23:01:55
【问题描述】:

我正在尝试对可变尺寸的图像执行卷积 (conv2d)。我有这些一维数组形式的图像,我想对它们进行卷积,但是我在形状上有很多麻烦。 这是我的conv2d代码:

tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')

其中x 是输入图像。 错误是:

ValueError: Shape must be rank 4 but is rank 1 for 'Conv2D' (op: 'Conv2D') with input shapes: [1], [5,5,1,32].

我想我可能会重塑x,但我不知道正确的尺寸。当我尝试这段代码时:

x = tf.reshape(self.x, shape=[-1, 5, 5, 1]) # example

我明白了:

ValueError: Dimension size must be evenly divisible by 25 but is 1 for 'Reshape' (op: 'Reshape') with input shapes: [1], [4] and with input tensors computed as partial shapes: input[1] = [?,5,5,1].

【问题讨论】:

  • conv2d 想要shape=[batch, height, width, channels] 的数据,因此如果可以选择,最好直接使用图像而不是将它们展平为一维数组。
  • 谢谢。问题是图像没有标准的高度或宽度,所以我无法提前告诉形状。

标签: python image tensorflow reshape convolution


【解决方案1】:

您不能将conv2d 与等级为 1 的张量一起使用。以下是文档中的描述:

在给定 4-D 输入和滤波器张量的情况下计算二维卷积。

这四个维度是[batch, height, width, channels](正如 Engineero 已经写过的)。

如果你事先不知道图片的尺寸,tensorflow 允许提供 动态 形状:

x = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='x')
with tf.Session() as session:
    print session.run(x, feed_dict={x: data})

在此示例中,创建了一个 4-D 张量 x,但只有通道数是静态已知的 (3),其他一切都在运行时确定。所以你可以将这个x 传递给conv2d,即使大小是动态的。

但还有另一个问题。你没有说你的任务,但是如果你正在构建一个卷积神经网络,恐怕你需要知道输入的大小来确定所有池化操作后 FC 层的大小——这个大小必须是静态的。如果是这种情况,我认为最好的解决方案实际上是在将输入传递到卷积网络之前将其缩放到一个通用大小。

更新:

由于不清楚,以下是如何将任何图像重塑为 4-D 数组。

a = np.zeros([50, 178, 3])
shape = a.shape
print shape    # prints (50, 178, 3)
a = a.reshape([1] + list(shape))
print a.shape  # prints (1, 50, 178, 3)

【讨论】:

  • 我按照你说的做了,但是我得到了这个错误:ValueError: Cannot feed value of shape (50, 178) for Tensor 'Placeholder:0', which has shape '(?, ?, ?, 3)'.
  • 我猜(150, 178) 是你的图片尺寸。它有多少个频道?如果只有一个,您需要将其重塑为 (1, -1, -1, 1) - 这将是一批。
  • 我的错。我将图像转换为 rgb,现在我得到了这个:ValueError: Cannot feed value of shape (50, 178, 3) for Tensor 'Placeholder:0', which has shape '(?, ?, ?, 3)'
  • 您忘记了批次的维度:reshape([1, -1, -1, -1]) 将使其排名第 4。
  • 你的意思是我需要这样重塑吗?:self.x: tf.reshape(self.__training_set[index], [1, -1, -1, -1])。因为我无法将张量提供给 feed_dict。
猜你喜欢
  • 1970-01-01
  • 2018-05-14
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-27
  • 1970-01-01
相关资源
最近更新 更多