使用tf.cast转int32触发无法JSON序列化错误如何解决
问题解决:TensorFlow取整结果可JSON序列化方案
根因分析
tf.math.round()默认输出浮点型张量,因此取整结果会带有.0后缀- 直接通过
tf.cast(..., dtype="int32")转换后得到的是TensorFlow张量类型,Python标准JSON序列化器(Tornado的finish方法默认调用)不支持该类型,因此触发TypeError。
解决方法
单值转换
针对单个数值的取整场景,转换逻辑如下:
# 原始取整操作 rounded_val = tf.math.round(input_tensor) # 转换为可JSON序列化的Python原生整型 result = int(tf.cast(rounded_val, dtype="int32").numpy())
批量值转换
针对多值张量的批量取整场景,转换逻辑如下:
# 批量取整操作 rounded_batch = tf.math.round(input_batch_tensor) # 转换为可JSON序列化的Python原生整型列表 result = tf.cast(rounded_batch, dtype="int32").numpy().tolist()
注意事项
.numpy()是TensorFlow官方提供的标准张量取值方法,属于TensorFlow生态内的合法操作- 转换得到的Python原生int/int列表可直接传入Tornado的
finish方法,不会触发类型错误 - 若运行在图执行模式下,需在会话中执行张量得到取值后,再做上述转换即可。
内容的提问来源于stack exchange,提问作者Sid Anand
相关产品推荐
相关产品推荐

