[Python] json 報錯'xxx is not JSON serializable'的處理方法


 

 

1 predictions = self.model.predict(x_data, verbose=0)[0] 
2 y_pred_idx = np.argmax(predictions)
3 y_pred_prob = predictions[y_pred_idx]
4 y_pred_label = self.le.inverse_transform(y_pred_idx) 
5 res = OrderedDict()
6 res['first'] = self.first_label2name[y_pred_label[0]]
7 res['second'] = self.second_label2name[y_pred_label]
8 res['probability'] = y_pred_prob
9 out.write(json.dumps(res, ensure_ascii=False) + '\n')

報錯:'0.80454153 is not JSON serializable'

 

輸出y_pred_prob的類別:<type 'numpy.float32'>

參考https://stackoverflow.com/questions/27050108/convert-numpy-type-to-python/27050186#27050186中類似問題的解決方案,有個回答中提到:

Ultimately, it looks like json is telling you that an int isn't serializable, but really, it's telling you that this particular np.int32 (or whatever type you actually have) isn't serializable. (No real surprise there -- No np.int32 is serializable). 

 

可以知道,json不能對np.int32或者np.float32等類型進行序列化,可以通過自定義serializer或者直接類型轉換來解決。

因此,在第8行顯式地把數據轉為float類型:res['probability'] = float(y_pred_prob)即可

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM