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

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

我有一个 Tensor,我正试图将其另存为 TensorProto,如图所示 here

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

错误:

    <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'

我做错了什么?

x的类型是tensor,不是tensorProto。只需将张量转换为 tensorProto 在序列化之前。关注这个link

x = tf.make_tensor_proto(x)

更新

您的 tensorflow 运行正在非急切模式下运行。因此,张量的类型是tensorflow.python.framework.ops.tensor。在这种情况下,Tensorflow 只定义了计算方法(aka graph),例如加减乘除等运算的组合。它不会进行任何计算,因为图中没有数据流。所以你需要在 eager 模式下 运行 并获得 eager tensor。下面的示例可能对您有所帮助。

非急切模式

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.

急切模式

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))