如何有效地创建一个收集许多矩阵并堆叠它们的numpy张量,总是添加新的矩阵。这对于管理批量图像很有用,例如,每个图像都是3D矩阵。堆叠 N ,3D图像(每个RGB平面的一个维度)一起创建一个4D矩阵。
以下the base form只是简单地将矩阵附加到新维度,创建比原始维度更高维度的最终矩阵。这是some information on the np.newaxis
functionality。
答案 0 :(得分:-2)
我知道有两种好方法,它们使用问题链接中的某些方式作为构建块。
如果你创建一个数组,例如具有3个维度并且在运行中希望继续将这些单个结果相互附加,从而创建4d张量,然后在应用问题中发布的答案之前,您需要为第一个阵列进行少量初始设置。 / p>
一种方法是将所有单个矩阵存储在一个列表中(随后附加),然后只需使用np.array
组合它们:
def list_version(input_data, N):
outputs = []
for i in range(N):
one_matrix = function_creating_single_matrix(arg1, arg2)
outputs.append(one_matrix)
return np.array(outputs)
第二种方法使用np.newaxis
将第一个矩阵(例如3d)扩展为4d。然后,随后的三维矩阵可以np.concatenate
逐个def concat_version(input_data, N):
for i in range(N):
if i == 0:
results = function_creating_single_matrix(arg1, arg2)
results = results[np.newaxis,...] # add the new dimension
else:
output = function_creating_single_matrix(arg1, arg2)
results = np.concatenate((results, output[np.newaxis,...]), axis=0)
# the results are growing the the first dimension (=0)
return results
。它们还必须在与第一个矩阵相同的维度上进行扩展 - 最终结果在此维度中增长。这是一个例子:
%%timeit
我还使用Jupyter function_creating_single_matrix() = np.ones(shape=(10, 50, 50))
单元格对性能进行了比较。为了使伪代码在上面工作,我刚刚创建了一个简单的矩阵,用矩阵填充,以便彼此附加:
%%timeit -n 100
resized = list_version(N=100)
# 4.97 ms ± 25.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit -n 100
resized = concat_version(N=100)
# 96.6 ms ± 144 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
然后我也可以比较结果以确保它是相同的。
list_output = list_version(N=100)
concat_output = concat_version(N=100)
np.array_equal(list_output, concat_output)
# True
所以似乎列表方法快了~20倍! ......至少在矩阵幅度的这些尺度上
在这里,我们看到函数返回相同的结果:
cProfile
我还在函数上运行np.concatenate
,似乎原因是import fitsio, numpy
from fitsio import FITS,FITSHDR
fits = FITS('test.fits','rw')
data = numpy.zeros(1, dtype=[('index','i4')])
data[0]['index'] = 1
fits.write(data)
fits.close()
花了很多时间复制矩阵。然后我将其追溯到the underlying C code。