以人类可读的格式保存 numpy 数组字典



这不是一个重复的问题。我环顾四周,发现了这个问题,但是savezpickle实用程序使人类无法读取文件。我想将其保存在一个.txt文件中,该文件可以加载回python脚本中。所以我想知道python中是否有一些实用程序可以促进这项任务并保持写入文件可读性。

numpy 数组的字典包含 2D 数组。

编辑:
根据克雷格的回答,我尝试了以下方法:

import numpy as np 
W = np.arange(10).reshape(2,5)
b = np.arange(12).reshape(3,4)
d = {'W':W, 'b':b}
with open('out.txt', 'w') as outfile:
    outfile.write(repr(d))
f = open('out.txt', 'r')
d = eval(f.readline())
print(d) 

这给出了以下错误:SyntaxError: unexpected EOF while parsing
out.txt确实如预期的那样包含字典。如何正确加载它?

编辑2:遇到一个问题:如果大小很大,Craig 的答案会截断数组。out.txt显示前几个元素,用...替换中间元素,并显示最后几个元素。

使用 repr() 将字典转换为字符串并将其写入文本文件。

import numpy as np
d = {'a':np.zeros(10), 'b':np.ones(10)}
with open('out.txt', 'w') as outfile:
    outfile.write(repr(d))

您可以将其读回并转换为带有eval()的字典:

import numpy as np
f = open('out.txt', 'r')
data = f.read()
data = data.replace('array', 'np.array')
d = eval(data)

或者,您可以直接从numpy导入array

from numpy import array
f = open('out.txt', 'r')
data = f.read()
d = eval(data)

H/T:如何将 NumPy 数组的字符串表示转换为 NumPy 数组?

处理大型数组

默认情况下,numpy汇总长度超过 1000 个元素的数组。您可以通过调用S大于数组大小的numpy.set_printoptions(threshold=S)来更改此行为。例如:

import numpy as np 
W = np.arange(10).reshape(2,5)
b = np.arange(12).reshape(3,4)
d = {'W':W, 'b':b}
largest = max(np.prod(a.shape) for a in d.values()) #get the size of the largest array
np.set_printoptions(threshold=largest) #set threshold to largest to avoid summarizing
with open('out.txt', 'w') as outfile:
    outfile.write(repr(d))    
np.set_printoptions(threshold=1000) #recommended, but not necessary

H/T:在 python 3 中将 numpy 数组列表转换为字符串时的省略号

最新更新