Search code examples
pythonprotocol-buffers

How to transfer tensorflow.TensorProto to custom xxx.TensorProto?


I define a custom xxx.TensorProto which has the same struct as tensorflow.TensorProto. I use tf.make_tensor_proto to transfer a ndarray to tensorflow.TensorProto, but when I try to write tensorflow.TensorProto to xxx.TensorProto, it always fail.

proto file:

package xxx;
message Tensor {
  string name = 1;     
  TensorProto tensor_proto = 2;
}

e.g.,

val = numpy.array([0.1, 0.2, 0.3])
xxxtp = xxx.Tensor()
xxxtp.tensor_proto  = tf.make_tensor_proto(val)

This result in : AttributeError: Assignment not allowed to field "tensor_proto" in protocol message object.

While I use xxxtp.tensor_proto.CopyFrom(tf.make_tensor_proto(val)), it result in: TypeError: Parameter to CopyFrom() must be instance of same class: expected xxx.TensorProto got tensorflow.TensorProto.

A possible way is to split each item in the xxx.TensorProto to assign the value.

e.g.,

tp = tf.make_tensor_proto(val)
xxxtp.tensor_proto.dtype = tp.dtype
....

Solution

  • xxxtp.tensor_proto.ParseFromString(tp.SerializeToString())
    

    Serialize to string then parse back.