【问题标题】:How to use numpy arrays as input to Tensorflow CNN without mismatched dimensions如何使用 numpy 数组作为 Tensorflow CNN 的输入而不会出现尺寸不匹配的问题
【发布时间】:2026-01-16 22:10:02
【问题描述】:

我有一个张量流卷积网络的输入作为 rank-4 张量(32、32、3、73257)(73257 来自 imgs 的数量),它们是 numpy 数组,但我的 x 输入的占位符变量是 2-d, (无,3072)。 3072 来自于 img 高度 x img 宽度 x 通道。我的问题是,如何重塑或使用图像以使其与占位符兼容?

附:这些图像来自 SVHN 裁剪的 32x32 数据集

images = np.array(features, dtype=np.float32)
...
x = tf.placeholder(tf.float32, shape=[None, 3072])
...
for _ in range(1000):
  batch = next_batch(50, images, labels)
  train_step.run(feed_dict={x: batch[0], y_: batch[1]})
...
with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  for i in range(20000):
    batch = next_batch(50, images, labels)
    if i % 100 == 0:
      train_accuracy = accuracy.eval(feed_dict={
          x: batch[0], y_: batch[1], keep_prob: 1.0})
      print('step %d, training accuracy %g' % (i, train_accuracy))
    train_step.run(feed_dict={x: images, y_: labels, keep_prob: 0.5})

【问题讨论】:

    标签: python arrays numpy tensorflow


    【解决方案1】:

    假设您有 73257 张 32 x 32 像素的图像,包含 3 个波段(例如 rgb)。你可以做一个

    input = tf.transpose(input, [3, 0, 1, 2])
    

    首先带来最后一个维度。然后张量应该看起来像 (73257, 32, 32, 3)。

    那就做吧

    input = tf.reshape(input, [-1, 3072])
    

    减小维度。然后张量应该看起来像 (73257, 3072)。

    【讨论】:

    • 知道了!感谢您的帮助
    最近更新 更多