How to convert tensorflow tensor to bytes?

Viewed 3107

In numpy converting a np tensor to bytes can be done as follows:

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)

In tensorflow you can do this to create the tensor, but how can you convert the result to a bytearray?

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

#Do conversion here

Also: I'm also working on a tf model wrapped in @tf.function, so eager execution is not enabled, which means I can't use the .numpy() method on the tensor.

1 Answers
tensorByteProto = tf.io.serialize_tensor(a)

To extract bytes from TensorProto use tensorByteProto.tensor_content

Related