使用C++部署Keras或TensorFlow模型
本文介绍如何在C++环境中部署Keras或TensorFlow模型。
一、对于Keras,
第一步,使用Keras搭建、训练、保存模型。
model.save('./your_keras_model.h5')
第二步,冻结Keras模型。
from keras.models import load_model
import tensorflow as tf
from tensorflow.python.framework import graph_io
from keras import backend as K def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
from tensorflow.python.framework.graph_util import convert_variables_to_constants
graph = session.graph
with graph.as_default():
freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
output_names = output_names or []
output_names += [v.op.name for v in tf.global_variables()]
input_graph_def = graph.as_graph_def()
if clear_devices:
for node in input_graph_def.node:
node.device = ""
frozen_graph = convert_variables_to_constants(session, input_graph_def, output_names, freeze_var_names)
return frozen_graph K.set_learning_phase(0)
keras_model = load_model('./your_keras_model.h5')
print('Inputs are:', keras_model.inputs)
print('Outputs are:', keras_model.outputs) frozen_graph = freeze_session(K.get_session(), output_names=[out.op.name for out in model.outputs])
graph_io.write_graph(frozen_graph, "./", "your_frozen_model.pb", as_text=False)
二、对于TensorFlow,
1、使用TensorFlow搭建、训练、保存模型。
saver = tf.train.Saver()
saver.save(sess, "./your_tf_model.ckpt")
2、冻结TensorFlow模型。
python freeze_graph.py --input_checkpoint=./your_tf_model.ckpt --output_graph=./your_frozen_model.pb --output_node_names=output_node
三、使用TensorFlow的C/C++接口调用冻结的模型。这里,我们向模型中输入一张经过opencv处理的图片。
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace tensorflow; int main(int argc, char* argv[]){
// tell the network that it is not training
phaseTensor = Tensor(DT_BOOL, TensorShape());
auto phaseTensorPointer = phaseTensor.tensor<bool, 0>();
phaseTensorPointer(0) = false; // read the input image
cv::Mat img = imread('./your_input_image.png', 0);
input_image_height = img.size().height;
input_image_width = img.size().width;
input_image_channels = img.channels();
imageTensor = Tensor(DT_FLOAT, TensorShape({1, input_image_height, input_image_width, input_image_channels})); // convert the image to a tensor
float * imageTensorPointer = imageTensor.flat<float>().data();
cv::Mat imageTensorMatWarpper(input_image_height, input_image_width, CV_32FC3, imageTensorPointer);
img.convertTo(imageTensorMatWarpper, CV_32FC3); // construct the input
string input_node_name1 = "input tesnor name1";
string input_node_name2 = "input tensor name2";
std::vector<std::pair<string, Tensor>> inputs;
inputs = {{input_node_name1, phaseTensor}, {input_node_name2, imageTensor},}; // start a new session
Session* session;
Status status = NewSession(SessionOptions(), &session);
if (!status.ok()) {
cout << "NewSession failed! " << status.error_message() << std::endl;
}
// read the frozen graph
GraphDef graph_def;
status = ReadBinaryProto(Env::Default(), "./your_frozen_model.pb", &graph_def);
if (!status.ok()) {
cout << "ReadBinaryProto failed! " << status.error_message() << std::endl;
}
// initialize the session graph
status = session->Create(graph_def);
if (!status.ok()) {
cout << "Create failed! " << status.error_message() << std::endl;
} // define the output
string output_node_name1 = "output tensor name1";
std::vector<tensorflow::Tensor> outputs; // run the graph
tensorflow::Status status = session->Run(inputs, {output_node_name1}, {}, &outputs);
if (!status.ok()) {
cout << "Run failed! " << status.error_message() << std::endl;
} // obtain the output
Tensor output = std::move(outputs[0]);
tensorflow::StringPiece tmpBuff = output.tensor_data();
const float* final_output = reinterpret_cast<const float*>(tmpBuff.data()); //for classification problems, the output_data is a tensor of shape [batch_size, class_num]
/*
auto scores = outputs[0].flat<float>();
*/
session->Close();
return 0;
}
使用C++部署Keras或TensorFlow模型的更多相关文章
- 在android上跑 keras 或 tensorflow 模型
		https://groups.google.com/forum/#!topic/keras-users/Yob7mIDmTFs http://talc1.loria.fr/users/cerisara ... 
- Tensorflow 模型线上部署
		获取源码,请移步笔者的github: tensorflow-serving-tutorial 由于python的灵活性和完备的生态库,使得其成为实现.验证ML算法的不二之选.但是工业界要将模型部署到生 ... 
- TensorFlow模型部署到服务器---TensorFlow2.0
		前言  当一个TensorFlow模型训练出来的时候,为了投入到实际应用,所以就需要部署到服务器上.由于我本次所做的项目是一个javaweb的图像识别项目.所有我就想去寻找一下java调用Tenso ... 
- 移动端目标识别(1)——使用TensorFlow Lite将tensorflow模型部署到移动端(ssd)之TensorFlow Lite简介
		平时工作就是做深度学习,但是深度学习没有落地就是比较虚,目前在移动端或嵌入式端应用的比较实际,也了解到目前主要有 caffe2,腾讯ncnn,tensorflow,因为工作用tensorflow比较多 ... 
- 移动端目标识别(2)——使用TENSORFLOW LITE将TENSORFLOW模型部署到移动端(SSD)之TF Lite Developer Guide
		TF Lite开发人员指南 目录: 1 选择一个模型 使用一个预训练模型 使用自己的数据集重新训练inception-V3,MovileNet 训练自己的模型 2 转换模型格式 转换tf.GraphD ... 
- 使用tensorflow-serving部署tensorflow模型
		使用docker部署模型的好处在于,避免了与繁琐的环境配置打交道.使用docker,不需要手动安装Python,更不需要安装numpy.tensorflow各种包,直接一个docker就包含了全部.d ... 
- 【tensorflow-转载】tensorflow模型部署系列
		参考 1. tensorflow模型部署系列: 完 
- TensorFlow Serving实现多模型部署以及不同版本模型的调用
		前提:要实现多模型部署,首先要了解并且熟练实现单模型部署,可以借助官网文档,使用Docker实现部署. 1. 首先准备两个你需要部署的模型,统一的放在multiModel/文件夹下(文件夹名字可以任意 ... 
- 在R中使用Keras和TensorFlow构建深度学习模型
		一.以TensorFlow为后端的Keras框架安装 #首先在ubuntu16.04中运行以下代码 sudo apt-get install libcurl4-openssl-dev libssl-d ... 
随机推荐
- SaltStact自动化运维工具01
			什么是saltstackSaltstack是基于python开发的一套C/S架构配置管理工具使用SSL证书签方的方式进行认证管理底层使用ZeroMQ消息队列pub/sub方式通信 – 号称世界 ... 
- 【转】【Oracle 集群】Oracle 11G RAC教程之集群安装(七)
			原文地址:http://www.cnblogs.com/baiboy/p/orc7.html 阅读目录 目录 集群安装 参考文献 相关文章 Oracle 11G RAC集群安装(七) 概述:写下本文档 ... 
- CreateFile打开文件或者打开目录
			一.打开目录 参数列表: lpFileName String 要打开的文件的名字 dwDesiredAccess Long 如果为 GENERIC_READ 表示允许对设备进行读访问:如果为 GENE ... 
- MooFest 树状数组 + 前缀和
			比较友好的数据结构题 建议读者好好思考思考--. 可以分析出与前缀和的关系, 之后就愉快的套起树状数组辣 #include <cstdio> #include<queue> # ... 
- mysql数据库重点监控
			1. QPS 每秒钟查询数量 查询总数/秒数 queries per seconds show global status like 'Question%' 2.TPS 每秒钟的事物数 ... 
- Laravel的维护模式
			1.开启维护模式: php artisan down 2.关闭维护模式:php artisan up 3.当应用处于维护模式时,所有的路由都会指向一个自定义的视图.这对于更新应用或执行维护任务时临时 ... 
- AMPL下载使用
			AMPL下载使用 依次执行以下操作 wget https://ampl.com/demo/amplide.linux64.tgz tar xzf amplide.linux64.tgz cd ampl ... 
- 【Educational Codeforces Round 48 (Rated for Div. 2) D】Vasya And The Matrix
			[链接] 我是链接,点我呀:) [题意] 告诉你每一行.每一列的异或和. 让你求出一个符合要求的原矩阵. [题解] 显然应该有 a1^a2^....^an = b1^b2^....^bn 也即两边同时 ... 
- @PostConstruct 和  @PreDestroy 指定初始化和销毁方法
			通过实现 @PostConstruct 和 @PreDestroy 注解,也可以指定 bean 的初始化和销毁方法 一.Student 类 public class Student{ public S ... 
- windows无法开机解决方法
			电脑启动弹出错误Ntldr is missing , 解决方法:重新从xp中拷贝一个出来粘贴上就行 电脑启动弹出错误Ntldr is compressed ,表示分区中的文件被压缩了 解决方法:首先把 ... 
