一个numpy int64的坑

原文链接: https://my.oschina.net/Kanonpy/blog/1543791

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

今天跑一个tensorflow代码,由于最后结果需要导出为json的文件,所以采用了json.dumps直接写文件,但是一直报错:

Traceback (most recent call last):
  File "predict_test.py", line 62, in 
    json.dump(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/encoder.py", line 427, in _iterencode
    yield from _iterencode_list(o, _current_indent_level)
  File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/encoder.py", line 324, in _iterencode_list
    yield from chunks
  File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/encoder.py", line 403, in _iterencode_dict
    yield from chunks
  File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/encoder.py", line 324, in _iterencode_list
    yield from chunks
  File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/encoder.py", line 436, in _iterencode
    o = _default(o)
  File "/home/tensorflow/.pyenv/versions/3.5.3/lib/python3.5/json/encoder.py", line 179, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: 26 is not JSON serializable

一个numpy int64的坑_第1张图片

蒙蔽了很久,怎么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]
    submit.append(diction)

with open('submit.plk','w') as fw:
    json.dump(submit, fw)

好像没有什么问题呀~??

做了个小测试:

In [2]: a = submit[1]

In [3]: a
Out[3]: 
{'image_id': 'c532ed79f6c54fb3cf8c45004656e385079a5284.jpg',
 'label_id': [25, 13, 15]}

In [4]: b = {'image_id': 'c532ed79f6c54fb3cf8c45004656e385079a5284.jpg',
   ...:  'label_id': [25, 13, 15]}

In [5]: json.dumps(b)
Out[5]: '{"image_id": "c532ed79f6c54fb3cf8c45004656e385079a5284.jpg", "label_id": [25, 13, 15]}'

In [6]: a == b
Out[6]: True

In [7]: json.dumps(a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
...
TypeError: 25 is not JSON serializable

明明a 的值 和b 相等,为什么b就可以json.dumps,而 a json.dumps报错,懵逼一会,想想要不查看下25这个对象,原来对于a来说 25 是一个!!!

被狠狠地坑了半个小时~~由于平时做数据处理大家会经常用到numpy的array,所以大家也要注意,虽然都是整形,但numpy.int64和python的整数是不一样的,解决方案,可以用astype('in32t')或者直接用python的int()方法。

转载于:https://my.oschina.net/Kanonpy/blog/1543791

你可能感兴趣的:(一个numpy int64的坑)