Best way to convert TensorProto to TensorFlow tensor

Viewed 932

As far as I can tell, there are at least two different ways to recover a Tensor from a TensorProto in Tensorflow 2.3. Say, for the sake of example, that we have

tensor = tf.range(10)
tproto = tf.make_tensor_proto(tensor)

Then:

  • You can use tf.make_ndarray like so

tf.constant(tf.make_ndarray(tproto))

  • Or you can use tf.io.parse_tensor like so

tf.io.parse_tensor(tproto.SerializeToString(), out_type=tf.int32)

I feel both of these are a bit artificial, since in the former you end up with an intermediate numpy array, and in the latter you have to serialize the TensorProto to a string and parse it back. Additionally, parse_tensor won't automatically recover the correct data type from the TensorProto. So:

  1. Is there a function to do the conversion in a single step? I'd like to see something like tf.from_tensor_proto doing the conversion all at once optimizing for speed and memory allocation (or, if tf.constant(tf.make_ndarray(tproto)) is the best you can do, just wrapping this up).

  2. Otherwise, which of the two options above should be preferred (in terms of efficiency, memory usage, etc.)?

0 Answers
Related