Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Python导出Tensorflow图以用于C++; < P>如何导出Python模型以供C++使用?< /P>_Python_C++_Export_Tensorflow_Deep Learning - Fatal编程技术网

从Python导出Tensorflow图以用于C++; < P>如何导出Python模型以供C++使用?< /P>

从Python导出Tensorflow图以用于C++; < P>如何导出Python模型以供C++使用?< /P>,python,c++,export,tensorflow,deep-learning,Python,C++,Export,Tensorflow,Deep Learning,我正在尝试做与本教程类似的事情: 我试图在C++ API中导入我自己的TF模型,而不是先开始。我调整了输入大小和路径,但奇怪的错误不断出现。我花了一整天的时间阅读StackOverflow和其他论坛,但都没用 我尝试了两种导出图形的方法 方法1:元图法 ...loading inputs, setting up the model, etc.... sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables())

我正在尝试做与本教程类似的事情:

我试图在C++ API中导入我自己的TF模型,而不是先开始。我调整了输入大小和路径,但奇怪的错误不断出现。我花了一整天的时间阅读StackOverflow和其他论坛,但都没用

我尝试了两种导出图形的方法

方法1:元图法

...loading inputs, setting up the model, etc....

sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())


for i in range(num_steps):  
  x_batch, y_batch = batch(50)  
  if i%10 == 0:
        train_accuracy = accuracy.eval(feed_dict={
        x:x_batch, y_: y_batch, keep_prob: 1.0})
        print("step %d, training accuracy %g"%(i, train_accuracy))
  train_step.run(feed_dict={x: x_batch, y_: y_batch, keep_prob: 0.5})

print("test accuracy %g"%accuracy.eval(feed_dict={
    x: features_test, y_: labels_test, keep_prob: 1.0}))

saver = tf.train.Saver(tf.all_variables())
checkpoint = 
   '/home/sander/tensorflow/tensorflow/examples/cat_face/data/model.ckpt'
    saver.save(sess, checkpoint)

   tf.train.export_meta_graph(filename=
   '/home/sander/tensorflow/tensorflow/examples/cat_face/data/cat_graph.pb',  
    meta_info_def=None,
    graph_def=sess.graph_def,
    saver_def=saver.restore(sess, checkpoint),
    collection_list=None, as_text=False)
方法1在尝试运行程序时产生以下错误:

[libprotobuf ERROR 
google/protobuf/src/google/protobuf/wire_format_lite.cc:532] String field 
'tensorflow.NodeDef.op' contains invalid UTF-8 data when parsing a protocol 
buffer. Use the 'bytes' type if you intend to send raw bytes. 
E tensorflow/examples/cat_face/main.cc:281] Not found: Failed to load 
compute graph at 'tensorflow/examples/cat_face/data/cat_graph.pb'
我还尝试了另一种导出图形的方法:

方法2:编写图表:

tf.train.write_graph(sess.graph_def, 
'/home/sander/tensorflow/tensorflow/examples/cat_face/data/', 
'cat_graph.pb', as_text=False)
这个版本实际上似乎加载了一些东西,但我得到一个关于未初始化变量的错误:

Running model failed: Failed precondition: Attempting to use uninitialized  
value weight1
[[Node: weight1/read = Identity[T=DT_FLOAT, _class=["loc:@weight1"], 
_device="/job:localhost/replica:0/task:0/cpu:0"](weight1)]]

首先,您需要使用以下命令将定义图形化到文件

with tf.Session() as sess:
//Build network here 
tf.train.write_graph(sess.graph.as_graph_def(), "C:\\output\\", "mymodel.pb")
然后,使用saver保存您的模型

saver = tf.train.Saver(tf.global_variables()) 
saver.save(sess, "C:\\output\\mymodel.ckpt")
然后,您的输出中将有两个文件,mymodel.ckpt和mymodel.pb

从下载freeze_graph.py并在C:\output\中运行以下命令。如果输出节点名称与您的不同,请更改它

python freeze\u graph.py--input\u graph mymodel.pb--input\u checkpoint mymodel.ckpt--output\u node\u names softmax/reforme\u 1--output\u graph mymodelforc.pb

您可以直接从C使用mymodelforc.pb

您可以使用以下C代码来加载proto文件

#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/cc/ops/image_ops.h"

Session* session;
NewSession(SessionOptions(), &session);

GraphDef graph_def;
ReadBinaryProto(Env::Default(), "C:\\output\\mymodelforc.pb", &graph_def);

session->Create(graph_def);
现在您可以使用会话进行推理

您可以按如下方式应用推理参数:

// Same dimension and type as input of your network
tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({ 1, height, width, channel }));
std::vector<tensorflow::Tensor> finalOutput;

// Fill input tensor with your input data

std::string InputName = "input"; // Your input placeholder's name
std::string OutputName = "softmax/Reshape_1"; // Your output placeholder's name

session->Run({ { InputName, input_tensor } }, { OutputName }, {}, &finalOutput);

// finalOutput will contain the inference output that you search for
//与网络输入相同的维度和类型
tensorflow::Tensor input_Tensor(tensorflow::DT_FLOAT,tensorflow::TensorShape({1,高度,宽度,通道}));
std::矢量最终输出;
//用输入数据填充输入张量
std::string InputName=“输入”//输入占位符的名称
std::string OutputName=“softmax/reformate_1”;//输出占位符的名称
会话->运行({InputName,input_tensor}},{OutputName},{},&finalOutput);
//finalOutput将包含您搜索的推理输出
您可以尝试以下操作(修改输出层的名称):


您可以发现OpenCV的模块非常有用。 它使加载和使用用Tensorflow(和其他框架)开发的预训练模型变得简单

可用于C++程序。


这是一个教程。

有“方法3:使用冻结图”。这避免了使用变量和运行恢复操作——啊,我已经看到了。但我很难找到如何填写它的参数,就像我不知道在导出元图中每个参数都要填写什么一样。你知道这方面的一些示例代码吗?这里有一个示例:非常感谢Yaroslav。我试试看。C++程序是否等同于教程中的程序?好吧,看来冻结图真的很有效。。伟大的不过,在C++中运行图时,我确实遇到了另一个错误。它说输入图像的类型错误,应该是提要dict。解决这个问题的好方法是什么?我应该改变C++中的某些东西,还是在Python中设置不同的图形?占位符变量在这里有问题吗?我将在下一个评论中显示错误。什么tensorflow版本Deniz?我问这个问题的原因是,我使用的包中的
saver.save
函数似乎创建了一个
.ckpt.meta
文件。我假设这与
saver.export\u meta\u graph
创建的东西是一样的……最近的互联网研究似乎表明R11和R12之间存在差异,但您最近编写了这篇文章,我想知道您使用的是哪个版本。我用当前最新的tensorflow源代码验证了这段代码。但是,CcP.Meta文件不需要C++运行,因为您已经使用“RealeSyGrand”导出。我将更新代码以防止混淆
import os
import tensorflow as tf
from tensorflow.python.framework import graph_util


def load_graph_def(model_path, sess=None):
    sess = sess if sess is not None else tf.get_default_session()
    saver = tf.train.import_meta_graph(model_path + '.meta')
    saver.restore(sess, model_path)


def freeze_graph(sess, output_layer_name, output_graph):
    graph = tf.get_default_graph()
    input_graph_def = graph.as_graph_def()

    # Exporting the graph
    print("Exporting graph...")
    output_graph_def = graph_util.convert_variables_to_constants(
        sess,
        input_graph_def,
        output_layer_name.split(","))

    with tf.gfile.GFile(output_graph, "wb") as f:
        f.write(output_graph_def.SerializeToString())


def freeze_from_checkpoint(checkpoint_file, output_layer_name):

    model_folder = os.path.basename(checkpoint_file)
    output_graph = os.path.join(model_folder, checkpoint_file + '.pb')

    with tf.Session() as sess:

        load_graph_def(checkpoint_file)

        freeze_graph(sess, output_layer_name, output_graph)


if __name__ == '__main__':
    freeze_from_checkpoint(
        checkpoint_file='/home/sander/tensorflow/tensorflow/examples/cat_face/data/model.ckpt',
        output_layer_name='???')