首页 > 解决方案 > 如何将张量流张量转换为字节?

问题描述

在 numpy 中,可以按如下方式将 np 张量转换为字节:

import tensorflow as tf
import numpy as np

b = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.uint8)
bytesArr = b.tobytes()
print(bytesArr)

在 tensorflow 中,您可以这样做来创建张量,但是如何将结果转换为字节数组?

a = tf.cast(tf.constant([[1.0, 2.0], [3.0, 4.0]]), tf.uint8)

#Do conversion here

另外:我也在研究一个包装在@tf.function 中的 tf 模型,所以没有启用急切执行,这意味着我不能在张量上使用 .numpy() 方法。

标签: pythonnumpytensorflow

解决方案


tensorByteProto = tf.io.serialize_tensor(a)

要从 TensorProto 中提取字节,请使用tensorByteProto.tensor_content


推荐阅读