首页 > 解决方案 > Cannot load protocol buffer with ReadBinaryProto Tensorflow

问题描述

I am having issues loading my protocol buffer file saved from a tensorflow model in C++. I can load and execute the .pb file in Python with no issues at all, however when trying to load it in C++ with the ReadBinaryProto function I get the error:

String field'tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version' 
   contains invalid UTF-8 data when parsing a protocol buffer. Use the 'bytes' 
   type if you intend to send raw bytes.

   Non-OK-status: LoadModel(session_inception, pathToGraph ) status: Data loss: 
   Can't parse E:/Projects/SampleTensorflow/tmp/latestmodel.pb as binary proto

I am using Tensorflow v1.10 and a sample of the C++ code is posted below, I have tried many different methods to save the .pb file including using the freeze_graph method and the tf.write_graph method, neither seem to fix the issue.

  tensorflow::Status LoadModel(tensorflow::Session *sess, std::string 
  graph_fn, std::string checkpoint_fn = "") {
  tensorflow::Status status;

  std::string graph_fn = "E:/Projects/SampleTensorflow/tmp/latestmodel.pb";      

  // Read in the protobuf graph
  tensorflow::MetaGraphDef graph_def;
  status = ReadBinaryProto(tensorflow::Env::Default(), graph_fn, 
                            &graph_def);

  if (status != tensorflow::Status::OK())
    return status;

  // Create the graph
  status = sess->Create(graph_def.graph_def());
  if (status != tensorflow::Status::OK())
      return status;

Thank you for any help!

标签: c++tensorflowprotocol-buffers

解决方案


A possible error is that the .pb file contains a GraphDef and not a MetaGraphDef.

To read a GraphDef, simply switch to

tensorflow::GraphDef graph_def;
status = ReadBinaryProto(tensorflow::Env::Default(), graph_fn, 
                        &graph_def);

The protobuf format is indeed just a container, which says nothing about what it contains. In tensorflow, this format is commonly used both to contain graphs and metagraphs, which can be confusing.


推荐阅读