繁体   English   中英

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

[英]Saving a dictionary of numpy arrays in human-readable format

不是重复的问题。 我四处看看,发现了这个问题 ,但是savezpickle实用程序使文件无法被人阅读。 我想将其保存为.txt文件,然后可以将其加载回python脚本中。 因此,我想知道python中是否有一些实用程序可以帮助完成此任务并保持书面文件对人类的可读性。

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

编辑:
根据Craig的回答 ,我尝试了以下操作:

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:碰到一个问题:如果大小很大,克雷格的答案会截断数组。 out.txt显示前几个元素,用...替换中间的元素,并显示最后几个元素。

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

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个元素的数组。 您可以通过调用numpy.set_printoptions(threshold=S)更改此行为,其中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数组列表转换为字符串时出现椭圆

暂无
暂无

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

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