gpt4 book ai didi

c++ - tensorflow 和 tflearn C++ API

转载 作者:行者123 更新时间:2023-11-30 03:22:10 25 4
gpt4 key购买 nike

一开始我对 tensorflow 和 python 都是新手。

我有一个包含 TFlearn DNN 网络的 Python 代码。我需要将该代码转换为 C++,以便稍后将其转换为用于移动应用程序开发的库。

我阅读了有关 tensorflow 的 C++ API(其中的文档非常模糊且不清楚)。所以我一行一行地尝试转换代码。

第一步是加载之前在python中训练和保存的保存模型(我不需要在c++中完成训练所以只加载tflearn模型就足够了)

保存文件的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')

加载模型 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')

这段代码在 python 中运行得很好,但模型保存文件实际上是模型文件夹中的 4 个文件,如下所示:

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

现在我来谈谈它的 C++ 部分。经过大量研究,我想出了以下代码:

#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;
}

现在对于我的问题,代码使用 bazel 构建正确编译(没有错误)(如 tensorflow C++ API 的“简短”解释中所述。但是当我尝试运行它时,找不到模型文件。

我在 C++ 中所做的正确吗?这是加载已保存模型的正确方法吗(我不知道为什么在保存过程中生成了 4 个文件)?或者还有其他方法吗?

是否有针对 tensorflow c++ API 的“完整和下降”手册?

最佳答案

如果您只是想加载一个已经训练好的模型,C++ 加载器已经存在。直接上tensorflow look herehere

Patwie 也有一个加载已保存模型的非常好的示例 Code from 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;
}

不幸的是,目前还没有针对 tensorflow c++ API 的“完整和下降”手册(AFAIK)

关于c++ - tensorflow 和 tflearn C++ API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51357669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com