Skip to main content
 首页 » 编程设计

python之如何在没有不匹配维度的情况下使用 numpy 数组作为 Tensorflow CNN 的输入

2024年08月19日34jyk

我将 tensorflow convnet 输入作为 rank-4 张量 (32, 32, 3, 73257)(73257 来自 img 的数量),它们是 numpy 数组,但我的 x 输入的占位符变量是二维的, (无,3072)。 3072 来自 img 高度 x img 宽度 x channel 。我的问题是,如何 reshape 或使用图像以使其与占位符兼容?

附言这些图像来自 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}) 

请您参考如下方法:

假设您有 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)。