2019独角兽企业重金招聘Python工程师标准>>>
今天跑一个tensorflow代码,由于最后结果需要导出为json的文件,所以采用了直接写文件,但是一直报错:
Traceback (most recent call last):
File "predict_test.py", line 62, in <module>
(submit, fw)
File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/__init__.py", line 178, in dump
for chunk in iterable:
File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/", line 427, in _iterencode
yield from _iterencode_list(o, _current_indent_level)
File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/", line 324, in _iterencode_list
yield from chunks
File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/", line 403, in _iterencode_dict
yield from chunks
File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/", line 324, in _iterencode_list
yield from chunks
File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/", line 436, in _iterencode
o = _default(o)
File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: 26 is not JSON serializable
蒙蔽了很久,怎么26这个数字不可以serializable??
定位到报错代码位置,报错代码如下:
top_indices = []
submit = []
for i in range(n):
diction = {}
diction["label_id"] = list(preds[i].argsort()[-3:][::-1])
diction["image_id"] = id_list[i]
(diction)
with open('','w') as fw:
(submit, fw)
好像没有什么问题呀~??
做了个小测试:
In [2]: a = submit[1]
In [3]: a
Out[3]:
{'image_id': '',
'label_id': [25, 13, 15]}
In [4]: b = {'image_id': '',
...: 'label_id': [25, 13, 15]}
In [5]: (b)
Out[5]: '{"image_id": "", "label_id": [25, 13, 15]}'
In [6]: a == b
Out[6]: True
In [7]: (a)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-373a2a7edfd2> in <module>()
...
TypeError: 25 is not JSON serializable
明明a 的值 和b 相等,为什么b就可以,而 a 报错,懵逼一会,想想要不查看下25这个对象,原来对于a来说 25 是一个<type 'numpy.int64'>!!!
被狠狠地坑了半个小时~~由于平时做数据处理大家会经常用到numpy的array,所以大家也要注意,虽然都是整形,但numpy.int64和python的整数是不一样的,解决方案,可以用astype('in32t')或者直接用python的int()方法。