繁体   English   中英

将numpy.arrays增量添加到保存文件

[英]Incremently appending numpy.arrays to a save file

我已经尝试了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个数组,但是当我多次加载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']

您对np.save所有调用np.save使用文件名,而不是文件句柄。 由于不重复使用文件句柄,因此每个保存都将覆盖文件,而不是将数组附加到文件句柄。

这应该工作:

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(f, prediction)

        current_iteration += 1
    if current_iteration == 5:
        break

尽管将多个数组存储在一个.npy文件中可能会有好处(我想在内存有限的情况下有好处), .npz 技术上讲 ,它们是用来存储一个数组的,您可以使用.npz文件( np.saveznp.savez_compressed )存储多个数组:

filename = 'testing.npz'
predictions = []
for (x, _), index in zip(train_generator, range(5)):
    prediction = base_model.predict(x)
    predictions.append(prediction)
np.savez(filename, predictions) # will name it arr_0
# np.savez(filename, predictions=predictions) # would name it predictions
# np.savez(filename, *predictions) # would name it arr_0, arr_1, …, arr_4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM