如何最有效地对大文件求和(100, 1024, 1024) .npz?有没有更好的文件格式来存储给定维度的Python数据?
我目前用它来对矩阵求和:
summed_matrix = np.sum([np.load(file) for file in files_list])
Run Code Online (Sandbox Code Playgroud)
这超出了我的可用内存。
目前,您一次加载所有文件,然后才开始求和。如果内存是一个问题,更好的方法是一次读取并添加一个:
summed_matrix = np.zeros((100, 1024, 1024))
for file in files_list:
summed_matrix += np.load(file)
Run Code Online (Sandbox Code Playgroud)
functools.reduce您可以尝试使用和生成器numpy.add:
from functools import reduce
summed_matrix = reduce(np.add, (np.load(file) for file in files_list))
# or functional-style
summed_matrix = reduce(np.add, map(np.load, files_list))
Run Code Online (Sandbox Code Playgroud)