如何将numpy数组连接成特定的形状?

时间:2017-04-01 05:11:25

标签: python numpy tensorflow mnist

我需要将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)

必须有一种简单的方法来实现我想要的东西,但我无法理解。

1 个答案:

答案 0 :(得分: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)

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

相关问题