如何将 numpy 数组连接成特定的形状?
How to concatenate numpy arrays into a specific shape?
我需要将 mnist
个图像值数组分配给以下变量...
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)
一定有一个简单的方法可以完成我想要的,但我想不通。
忘记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)
。
列表追加速度更快,更易于使用。
我需要将 mnist
个图像值数组分配给以下变量...
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)
一定有一个简单的方法可以完成我想要的,但我想不通。
忘记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)
。
列表追加速度更快,更易于使用。