【问题标题】:How to concatenate numpy arrays into a specific shape?如何将 numpy 数组连接成特定的形状?
【发布时间】:2017-04-01 05:11:24
【问题描述】:

我需要将mnist 图像值的数组分配给以下变量...

x = tf.get_variable("input_image", shape=[10,784], dtype=tf.float32)

问题是我需要筛选mnist数据集并提取10张数字2的图像并将其分配给x

这是我筛选数据集并提取数字 2 的方法...

while mnist.test.next_batch(FLAGS.batch_size):
    sample_image, sample_label = mnist.test.next_batch(10)
    # get number 2
    itemindex = np.where(sample_label == 1)

    if itemindex[1][0] == 1:
        # append image to numpy
        np.append(labels_of_2, sample_image)
    # if the numpy array has 10 images then we stop
    if labels_of_2.size == 10:
        break

# assign to variable
sess.run(tf.assign(x, labels_of_2))

问题是我认为我的逻辑有缺陷。我需要一个形状为[10, 784] 的数组来满足变量x 并且显然以下行不是这样做的方法...

np.append(labels_of_2, sample_image)

必须有一种简单的方法来完成我想要的,但我想不通。

【问题讨论】:

    标签: python numpy tensorflow mnist


    【解决方案1】:

    忘记np.append;收集列表中的图像

    alist = []
    while mnist.test.next_batch(FLAGS.batch_size):
        sample_image, sample_label = mnist.test.next_batch(10)
        # get number 2
        itemindex = np.where(sample_label == 1)
    
        if itemindex[1][0] == 1:
            alist.append(sample_image)
        # if the list has 10 images then we stop
        if len(alist) == 10:
            break
    
        labels_of_2 = np.array(alist)
    

    假设alist 中的数组都具有相同的大小,例如(784,),然后array 函数将生成一个形状为 (10, 784) 的新数组。如果图像是 (1,784),您可以改用 np.concatenate(alist, axis=0)

    列表追加更快更容易使用。

    【讨论】:

      猜你喜欢
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      相关资源
      最近更新 更多