简体   繁体   English

tensorflow和tflearn c ++ API

[英]tensorflow and tflearn c++ API

At first I am new on both tensorflow and python to start with. 首先,我是从tensorflow和python入手的。

I have a python code that contains a TFlearn DNN network. 我有一个包含TFlearn DNN网络的python代码。 I need to convert that code to C++ to later on convert it into a library to be used in mobile application development. 我需要将该代码转换为C ++,以便稍后将其转换为要在移动应用程序开发中使用的库。

I read about the C++ API for tensorflow (of which documentations are real vague and not clear). 我阅读了有关tensorflow的C ++ API(其中的文档确实含糊不清,尚不清楚)。 so I took the code line by line to try converting it. 所以我一行接一行地尝试转换代码。

The first step was loading the saved model that was was previously trained and saved in python (I don't need training to be done in c++ so just loading the tflearn model is enough) 第一步是加载先前已训练并保存在python中的已保存模型(我不需要使用c ++进行培训,因此只需加载tflearn模型就足够了)

The python code to save the file was as follows: 保存文件的python代码如下:

network = input_data(shape=[None, 100, 100, 1], name='input')
network = conv_2d(network, 32, 5, activation='relu')
network = avg_pool_2d(network, 2)
network = conv_2d(network, 64, 5, activation='relu')
network = avg_pool_2d(network, 2)
network = fully_connected(network, 128, activation='relu')
network = fully_connected(network, 64, activation='relu')
network = fully_connected(network, 2, activation='softmax',restore=False)
network = regression(network, optimizer='adam', learning_rate=0.0001,
                    loss='categorical_crossentropy', name='target')

model = tflearn.DNN(network, tensorboard_verbose=0)
model.fit(X, y.toarray(), n_epoch=3, validation_set=0.1, shuffle=True,
        show_metric=True, batch_size=32, snapshot_step=100,
        snapshot_epoch=False, run_id='model_finetuning')

model.save('model/my_model.tflearn')

To load the model python code was: 加载模型python代码是:

network = input_data(shape=[None, 100, 100, 1], name='input')
network = conv_2d(network, 32, 5, activation='relu')
network = avg_pool_2d(network, 2)
network = conv_2d(network, 64, 5, activation='relu')
network = avg_pool_2d(network, 2)
network = fully_connected(network, 128, activation='relu')
network = fully_connected(network, 64, activation='relu')
network = fully_connected(network, 2, activation='softmax')
network = regression(network, optimizer='adam', learning_rate=0.001,
                     loss='categorical_crossentropy', name='target')
model = tflearn.DNN(network, tensorboard_verbose=0)
model.load('model/my_model.tflearn')

and this code worked like a charm in python, yet the model save file was actually 4 files inside the model folder as follows: 并且此代码在python中就像一个魅力一样工作,但是模型保存文件实际上是model文件夹内的4个文件,如下所示:

model
|------------checkpoint
|------------my_model.tflearn.data-00000-of-00001
|------------my_model.tflearn.index
|------------my_model.tflearn.meta

now I come to the c++ part of it. 现在我来谈谈它的C ++部分。 After a lot of research I came up with the following code: 经过大量研究,我得出了以下代码:

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

#include <iostream>

using namespace tensorflow;
using namespace std;

int main()
{
    Session* session;
    Status status = NewSession(SessionOptions(), &session);
    if (!status.ok())
    {
        cerr << status.ToString() << "\n";
        return 1;
    }
    else
    {
        cout << "Session created successfully" << endl;
    }
    tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({1,100,100,1}));
    GraphDef graph_def;

    status = ReadBinaryProto(Env::Default(), "/home/user/PycharmProjects/untitled/model/my_model.tflearn", &graph_def);
    if (!status.ok())
    {
        cerr << status.ToString() << "\n";
        return 1;
    }
    else
    {
        cout << "Read Model File" << endl;
    }
    return 0;
}

And now for my questions, the code compile correctly (with no faults) using the bazel build (as described in the "Short" explanation of tensorflow C++ API. but when I tried to run it the model file is not found. 现在,对于我的问题,代码使用bazel构建(如tensorflow C ++ API的“简短”说明中所述)正确编译(没有错误),但是当我尝试运行它时,找不到模型文件。

Is what I did in c++ correct? 我在c ++中所做的正确吗? Is this the correct way to load the saved model (which I don't know why 4 files are generated during save)? 这是加载保存的模型的正确方法(我不知道为什么在保存过程中会生成4个文件)吗? or is there another approach to do it? 还是有其他方法可以做到?

Is there any "Full and descent" manual for the tensorflow c++ API? tensorflow c ++ API是否有“全面介绍”手册?

If you just want to load an already trained model, a c++ loader already exists. 如果只想加载已经训练好的模型,则已经存在c ++加载器。 Directly on tensorflow look here and here 直接在tensorflow上查看此处此处

Patwie also got a really good example for loading a saved model Code from Patwie . Patwie还提供了一个非常好的示例,可以从Patwie加载保存的模型代码

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

  // Read in the protobuf graph we exported
  tensorflow::MetaGraphDef graph_def;
  status = ReadBinaryProto(tensorflow::Env::Default(), graph_fn, &graph_def);
  if (status != tensorflow::Status::OK())
    return status;

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

  // restore model from checkpoint, iff checkpoint is given
  if (checkpoint_fn != "") {

    const std::string restore_op_name = graph_def.saver_def().restore_op_name();
    const std::string filename_tensor_name = graph_def.saver_def().filename_tensor_name();

    tensorflow::Tensor filename_tensor(tensorflow::DT_STRING, tensorflow::TensorShape());
    filename_tensor.scalar<std::string>()() = checkpoint_fn;

    tensor_dict feed_dict = {{filename_tensor_name, filename_tensor}};
    status = sess->Run(feed_dict,
                       {},
                       {restore_op_name},
                       nullptr);
    if (status != tensorflow::Status::OK())
      return status;
  } else {
    // virtual Status Run(const std::vector<std::pair<string, Tensor> >& inputs,
    //                  const std::vector<string>& output_tensor_names,
    //                  const std::vector<string>& target_node_names,
    //                  std::vector<Tensor>* outputs) = 0;
    status = sess->Run({}, {}, {"init"}, nullptr);
    if (status != tensorflow::Status::OK())
      return status;
  }

Unfortunatly there isn't a "full and descent" manual for tensorflow c++ API yet (AFAIK) 不幸的是,目前还没有用于tensorflow c ++ API的``全面和下降''手册(AFAIK)

I wrote the steps how to save a TFLearn checkpoint correctly: 我编写了如何正确保存TFLearn检查点的步骤:

...
model = tflearn.DNN(network)

class MonitorCallback(tflearn.callbacks.Callback):
  # Create an other session to clone the model and avoid effecting the training process
  with tf.Session() as second_sess:
    # Clone the current model
    model2 = model
    # Delete the training ops
    del tf.get_collection_ref(tf.GraphKeys.TRAIN_OPS)[:]
    # Save the checkpoint
    model2.save('checkpoint_'+str(training_state.step)+".ckpt")
    # Write a text protobuf to have a human-readable form of the model
    tf.train.write_graph(second_sess.graph_def, '.', 'checkpoint_'+str(training_state.step)+".pbtxt", as_text = True)
  return

mycb = MonitorCallback()
model.fit({'input': X}, {'target': Y}, n_epoch=500, run_id="mymodel", callbacks=mycb)
...

After you have the checkpoint, you can load in C++: 拥有检查点后,可以在C ++中加载:

https://github.com/kecsap/tensorflow_cpp_packaging#load-a-checkpoint-in-c https://github.com/kecsap/tensorflow_cpp_packaging#load-a-checkpoint-in-c

...and you it for inference: ...而您可以推断:

https://github.com/kecsap/tensorflow_cpp_packaging#inference-in-c https://github.com/kecsap/tensorflow_cpp_packaging#inference-in-c

You can also find example code for C and how to freeze a model then load in C++. 您还可以找到C的示例代码以及如何冻结模型然后在C ++中加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM