Search code examples
tensorflowonnx

AttributeError: 'Tensor' object has no attribute 'SerializeToString'


I have a Tensor which I'm trying to save as a TensorProto as shown here

print(type(x))
print('TensorProto:\n{}'.format(x))
# Save the TensorProto
with open('tensor.pb', 'wb+') as f:
    f.write(x.SerializeToString())

Error:

    <class 'tensorflow.python.framework.ops.Tensor'>
    (1, 118, 120, 80, 3)
    TensorProto:
    Tensor("images:0", shape=(?, ?, 120, 80, 3), dtype=float32)
    Traceback (most recent call last):
      File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
        return _run_code(code, main_globals, None,
      File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
        exec(code, run_globals)
      File "/home/harry/mm/Bosch_DL_HW_Benchmark/03_benchmark/03_code/evaluation/evaluate_network_actrec.py", line 218, in <module>
        f.write(x.SerializeToString())
      File "/home/harry/.local/lib/python3.8/site-packages/tensorflow/python/framework/ops.py", line 401, in __getattr__
        self.__getattribute__(name)
    AttributeError: 'Tensor' object has no attribute 'SerializeToString'

What am I doing wrong here?


Solution

  • The type of x is tensor, not tensorProto. Just convert tensor to tensorProto before serializing. Follow this link

    x = tf.make_tensor_proto(x)
    

    Update

    Your tensorflow is running in non eager mode. Therefore, the type of tensor is tensorflow.python.framework.ops.tensor. Under this circumstances,Tensorflow only defines the calculation method(aka graph) such as the combination of some operations like addition, subtraction, multiplication and division. It won't do any calculations because there is no data flow in the graph. So you need to run in eager mode and get eager tensor. An example may help you below.

    non eager mode

    import tensorflow as tf
    
    tf.compat.v1.disable_eager_execution()
    
    x = tf.constant(1)
    print(type(x))
    x = tf.make_tensor_proto(x)  # TypeError: Expected any non-tensor type, got a tensor instead.
    

    eager mode

    import tensorflow as tf
    
    tf.compat.v1.enable_eager_execution()
    
    x = tf.constant(1)
    print(type(x))
    x = tf.make_tensor_proto(x)
    print(type(x))