如果您想将 dict 中的张量数据保存到 JSON 文件中,一个简单的解决方案是递归地进入您的字典并使用正确的函数将您的数据转换为 Json 中可序列化的内容(例如,如果它只是用于保存字符串,则为字符串)。如果这是您真正想要做的(即保存您的数据),我确信 tensorflow 必须有一种方法将您的数据保存为泡菜文件。
以下代码用于将 dict 中的内容递归地转换为字符串,但您应该能够根据您的用例轻松修改和 numify、jsonify 等代码。我的用例是以人类可读的格式保存数据(而不仅仅是torch.save
):
#%%
def _to_json_dict_with_strings(dictionary):
"""
Convert dict to dict with leafs only being strings. So it recursively makes keys to strings
if they are not dictionaries.
Use case:
- saving dictionary of tensors (convert the tensors to strins!)
- saving arguments from script (e.g. argparse) for it to be pretty
e.g.
"""
if type(dictionary) != dict:
return str(dictionary)
d = {k: _to_json_dict_with_strings(v) for k, v in dictionary.items()}
return d
def to_json(dic):
import types
import argparse
if type(dic) is dict:
dic = dict(dic)
else:
dic = dic.__dict__
return _to_json_dict_with_strings(dic)
def save_to_json_pretty(dic, path, mode='w', indent=4, sort_keys=True):
import json
with open(path, mode) as f:
json.dump(to_json(dic), f, indent=indent, sort_keys=sort_keys)
def my_pprint(dic):
"""
@param dic:
@return:
Note: this is not the same as pprint.
"""
import json
# make all keys strings recursively with their naitve str function
dic = to_json(dic)
# pretty print
pretty_dic = json.dumps(dic, indent=4, sort_keys=True)
print(pretty_dic)
# print(json.dumps(dic, indent=4, sort_keys=True))
# return pretty_dic
import torch
# import json # results in non serializabe errors for torch.Tensors
from pprint import pprint
dic = {'x': torch.randn(1, 3), 'rec': {'y': torch.randn(1, 3)}}
my_pprint(dic)
pprint(dic)
输出:
{
"rec": {
"y": "tensor([[-0.3137, 0.3138, 1.2894]])"
},
"x": "tensor([[-1.5909, 0.0516, -1.5445]])"
}
{'rec': {'y': tensor([[-0.3137, 0.3138, 1.2894]])},
'x': tensor([[-1.5909, 0.0516, -1.5445]])}
相关链接:
https://discuss.pytorch.org/t/typeerror-tensor-is-not-json-serializable/36065/3或如何打印 JSON 文件?和https://github.com/fossasia/visdom/issues/554。