使用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 ...
随机推荐
- Vue2实例中的data属性三种写法与作用
<script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app ...
- python的包装和授权
包装:python为大家提供了标准数据类型,以及丰富的内置方法,其实在很多场景下我们都需要基于标准数据类型来定制我们自己的数据类型,新增/改写方法,这就用到了我们刚学的继承/派生知识(其他的标准类型均 ...
- Ubuntu中无法update的解决办法
我输入 sudo apt-get update 出现错误: /etc/apt$ sudo apt-get update Err http://security.ubuntu.com precise-s ...
- ssm整合shiro—实现认证和授权
1.简述 1.1 Apache Shiro是Java的一个安全框架.是一个相对简单的框架,主要功能有认证.授权.加密.会话管理.与Web集成.缓存等. 1.2 Shiro不会去维护用户.维护 ...
- 基本socket api
socket函数,为了执行网络I/O,一个进程必须做的第一件事就是调用socket函数,并且指定通信协议类型. #include<sys/socket.h> int socket (int ...
- HDU 4268 Alice and Bob(贪心+Multiset的应用)
题意: Alice和Bob有n个长方形,有长度和宽度,一个矩形能够覆盖还有一个矩形的条件的是,本身长度大于等于还有一个矩形,且宽度大于等于还有一个矩形.矩形不可旋转.问你Alice最多能覆盖Bo ...
- linux块设备的IO调度算法和回写机制
************************************************************************************** 參考: <Linux ...
- Highcharts数据表示(2)
Highcharts数据表示(2) 数据节点是图表中最小的元素.每一个数据节点都是一个数据单元. 它确定了图表中一个图形元素的各种信息.一个数据节点通常包含下面三类信息: 1.坐标位置信息 因为Hig ...
- C# WebQQ协议群发机器人(二)
本文出处http://blog.csdn.net/zhujunxxxxx/ 如需转载请注明出处! 接着上一篇http://blog.csdn.net/zhujunxxxxx/article/detai ...
- Cocos2d-x 3.0 红孩儿私家必修 - 第一章 初识Cocos2d-x 3.0project
第一章 初识Cocos2d-x 3.0project Cocos2d-x 3.0出来了,听说与之前版本号相比修改较大 做为一个游戏开发人员.我们应该欢迎Cocos2d-x持续的更新和强大,Coc ...