2017-04-01 30 views
0

我需要mnist图像值的数组指派给下面的变量...如何将numpy数组连接成特定的形状?

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

问题是我需要通过mnist数据集进行筛选的,并提取数字2的10个图像,并为其分配到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

忘记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)代替。

列表追加更快,更易于使用。