我已经尝试过 Hpaulji 概述的这种方法,但它似乎不起作用:
如何在python中将多个numpy文件附加到一个numpy文件中 https://stackoverflow.com/questions/42204368/how-to-append-many-numpy-files-into-one-numpy-file-in-python
基本上,我正在迭代生成器,对数组进行一些更改,然后尝试保存每个迭代的数组。
我的示例代码如下所示:
filename = 'testing.npy'
with open(filename, 'wb') as f:
for x, _ in train_generator:
prediction = base_model.predict(x)
print(prediction[0,0,0,0:5])
np.save(filename, prediction)
current_iteration += 1
if current_iteration == 5:
break
在这里,我经历了 5 次迭代,所以我希望能够保存5不同的数组。
我打印出了每个数组的一部分,用于调试目的:
[ 0. 0. 0. 0. 0.]
[ 0. 3.37349415 0. 0. 1.62561738]
[ 0. 20.28489304 0. 0. 0. ]
[ 0. 0. 0. 0. 0.]
[ 0. 21.98013496 0. 0. 0. ]
但是当我尝试加载数组时,如此处所述多次,如何在python中将多个numpy文件附加到一个numpy文件中 https://stackoverflow.com/questions/42204368/how-to-append-many-numpy-files-into-one-numpy-file-in-python,我收到 EOFERROR:
file = r'testing.npy'
with open(file,'rb') as f:
arr = np.load(f)
print(arr[0,0,0,0:5])
arr = np.load(f)
print(arr[0,0,0,0:5])
它只输出最后一个数组,然后输出 EOFERROR:
[ 0. 21.98013496 0. 0. 0. ]
EOFError: Ran out of input
print(arr[0,0,0,0:5])
我原本期望保存所有 5 个数组,但是当我多次加载 save .npy 文件时,我只得到最后一个数组。
那么,我应该如何保存新数组并将其附加到文件中?
编辑:使用“.npz”进行测试仅保存最后一个数组
filename = 'testing.npz'
current_iteration = 0
with open(filename, 'wb') as f:
for x, _ in train_generator:
prediction = base_model.predict(x)
print(prediction[0,0,0,0:5])
np.savez(f, prediction)
current_iteration += 1
if current_iteration == 5:
break
#loading
file = 'testing.npz'
with open(file,'rb') as f:
arr = np.load(f)
print(arr.keys())
>>>['arr_0']