Python 如何将tensorflow张量转换为字节?

Python 如何将tensorflow张量转换为字节?,python,numpy,tensorflow,Python,Numpy,Tensorflow,在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中,您可以这样创建张量,但如何将结果转换为bytearray a = tf.cast(tf.constant([[1.0, 2.0], [3.0

在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中,您可以这样创建张量,但如何将结果转换为bytearray

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

#Do conversion here
另外:我还在处理一个封装在@tf.function中的tf模型,因此没有启用“急切执行”,这意味着我不能在张量上使用.numpy()方法

tensorByteProto = tf.io.serialize_tensor(a)

要从TensorProto提取字节,请使用
tensorByteProto.tensor\u内容

第二个(tf.io.serialize\u tensor)选项(tf.io.serialize\u tensor)的值似乎与numpy.tobytes()命令的值不同。字节看起来不正确。请查看tf.io.serialize(a).tensor_内容是否有效。如果它不起作用,那么什么是不可接受的,因为如果您看到数据类型使用Python类型(val2test),那么它将显示为字节