stack
和concatenate
函数并不是非常高效。这也是有充分理由的,因为numpy试图保持数组内存连续以提高效率(请参见有关numpy中连续数组的链接)。l = []
for additional_X in ...:
l.append(addiional_X)
xdata_test = np.concatenate(l)
如果您提前拥有要连接的数组,我建议创建一个新数组,并用小数组填充总形状,而不是进行连接,因为每个连接操作都需要将整个数据复制到新的连续内存空间中。
First, calculate the total size of the first axis:
max_x = 0
for arr in list_of_arrays:
max_x += arr.shape[0]
Second, create the end container:
final_data = np.empty((max_x,) + xdata_test.shape[1:], dtype=xdata_test.dtype)
which is equivalent to (max_x, 40, 24, 24)
but dynamically typed.
Last, fill the numpy array:
curr_x = 0
for arr in list_of_arrays:
final_data[curr_x:curr_x+arr.shape[0]] = arr
curr_x += arr.shape[0]
上述循环将每个数组复制到先前定义的大数组的列/行中。
通过这样做,每个N
个数组都将复制到确切的最终目的地,而不是为每个连接创建临时数组。
concatenate
创建一个正确大小的空结果数组,然后将每个来源的数据复制到其中。 一次性连接操作会产生更少的复制。 - hpaulj