【问题标题】:How to use increase dimension for MNIST dataset?如何为 MNIST 数据集使用增加维度?
【发布时间】:2020-02-25 20:12:17
【问题描述】:

我尝试使用带有 Keras 的 Alexnet 的 MNIST 数据集,所以我应该改变维度(因为 MNIST 是灰度的,Alexnet 需要是 RGB 并且也是 227*227)。现在我得到了一些结果,numpy_imgs=(10,227,227,1) 但我应该像(10,227,227,3) 那样做,你可以在我的代码中看到我之前所做的, 谢谢。

  import tensorflow as tf
  import numpy as np
  from tensorflow.examples.tutorials.mnist import input_data

  mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
  batch=mnist.train.next_batch(10)
  X_batch = batch[0]
  batch_tensor = tf.reshape(X_batch, [10, 28, 28, 1])
  resized_images = tf.image.resize_images(batch_tensor, [227,227])
  with tf.Session() as sess:
      numpy_imgs = resized_images.eval(session=sess) # mnist images converted to numpy array

  r2=[]
  t=list(numpy_imgs)
  dim = np.zeros((227,227))
  for i in range(0,10):
      R=np.stack((t[i],dim,dim),axis=2)
      R=list(R)
      r2.append(R)
  y3=np.asarray(r2)

我在下面尝试了一些方法,但出现了“ValueError:所有输入数组必须具有相同的形状”之类的错误,我该如何解决?

【问题讨论】:

    标签: python tensorflow deep-learning image-resizing mnist


    【解决方案1】:

    看看tf.tile,它沿着它的一个维度重复一个张量:

    y3 = tf.tile(numpy_imgs, (1, 1, 1, 3))
    

    如果你想用归零的张量完成它,你应该使用tf.concat(或np.concatenate而不是stack。

    dim = np.zeros((227, 227, 2))
    for i in range(0, 10):
        R = np.concatenate((t[i], dim), axis=2)
        ...
    

    您甚至可以更简洁,一次处理所有批次:

    dim = np.zeros((10, 227, 227, 2))
    y3 = np.concatenate((numpy_imgs, dim), axis=3
    

    这是一个更一般的例子:

    import numpy as np
    
    def main():
        i = np.random.random((10, 227, 227, 1))
        dim = np.zeros((10, 227, 227, 2))
        print(i.shape)
        print(dim.shape)
        print(np.concatenate((i, dim), axis=3).shape)
    
    if __name__ == '__main__':
        main()
    
    (10, 227, 227, 1)
    (10, 227, 227, 2)
    (10, 227, 227, 3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多