我尝试了Hpaulji概述的方法,但似乎没有起作用:
如何在Python中将许多numpy文件附加到一个numpy文件中
基本上,我正在遍历生成器,对数组进行一些更改,然后尝试保存每次迭代的数组。
这是我的示例代码:
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文件中)时,我遇到了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个数组都能被保存,但是当我多次加载保存的.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']
.npy
进行存储? - jpp