我通过遍历一个tensorflow 2D数组创建了一个字典对象。现在,我需要将此字典对象作为对基于AngularJS的应用程序的响应来发送。我正在使用Python Flask创建后端。但是,当我使用jsonify函数时,出现以下异常:

TypeError: Object of type float32 is not JSON serializable


以下是我如何创建字典对象的摘要:

 with tf.Session() as sess:
    # Feed the audio data as input to the graph.
    #   predictions  will contain a two-dimensional array, where one
    #   dimension represents the input image count, and the other has
    #   predictions per class
    softmax_tensor = sess.graph.get_tensor_by_name(output_layer_name)
    predictions, = sess.run(softmax_tensor, {input_layer_name: wav_data})

    # Sort to show labels in order of confidence
    top_k = predictions.argsort()[-num_top_predictions:][::-1]
    result = {}
    for node_id in top_k:
      human_string = labels[node_id]
      score = predictions[node_id]
      result[human_string] = score

    return result


并且此代码段由以下控制器调用:

    @app.route("/predict")
    def predict():
        data = label_wav('static/tensorflow/0a2b400e_nohash_0.wav','static/tensorflow/conv_labels.txt','static/tensorflow/my_frozen_graph.pb','wav_data:0','labels_softmax:0',3)
        print(data) ## prints : {'left': 0.970138, 'yes': 0.02154522, '_unknown_': 0.0038029249}
        return jsonify(data), 200


有人可以告诉我如何序列化字典对象吗?

最佳答案

float32不是python中的内置类型,它是扩展类。要序列化用户定义的类,可以这样编写:

import json

class CJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, tf.float32):
            return ...
        else:
            return json.JSONEncoder.default(self, obj)

def json_dumps(data):
    return json.dumps(data, cls=CJSONEncoder)


实际上我之前从未使用过tensorflow,我现在在google上搜索过,得到了这个:

import tensorflow as tf

def convert_to_float(m):
    sess = tf.Session()
    with sess.as_default():
        ret = float(str(m.eval()))
    return ret


在我的环境中,它显示:

>>> m = tf.constant(1.1, dtype=tf.float32)
>>> sess = tf.Session()
>>> with sess.as_default():
...   ret = float(str(m.eval()))
...
>>> print(ret)
1.1


我不知道这是否合法,但希望能有所帮助。

10-07 15:16