使用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 ...
随机推荐
- day22 包,相对/绝对路径
目录 包 包被导入时发生的三件事 为什么要有包 相对路径 绝对路径 包 包是一个文件夹,也是一个模块,只是为了区分单个文件的模块,称之为包.因为单纯的文件夹无法作为模块,文件夹内的__init__.p ...
- Go 语言一本通
什么是GO语言? Go 是一个开源的编程语言,它能让构造简单.可靠且高效的软件变得容易. Go是从2007年末由Robert Griesemer, Rob Pike, Ken Thompson主持开发 ...
- 百面机器学习--跟课Task整理
涉及书中内容:特征工程&&模型评估 不同的特征如何进行特征工程? 特征是原始数据作为输入,特征工程的结果,作为输入供算法和模型使用. 对于数值型特征,为消除特征间的量纲影响,应对特征进 ...
- 洛谷P2827 蚯蚓 队列 + 观察
我们不难发现先被切开的两半一定比后被切开的两半大,这样就天然的生成了队列的单调性,就可以省去一个log.所以,我们开三个队列,分别为origin,big,smallorigin, big, small ...
- 人脸识别中的harr特征提取(转)
影响AdaBoost人脸检测训练算法速度很重要的两方面是特征选取和特征计算.选取的特征为矩特征为Haar特征,计算的方法为积分图. (1)Haar特征: Haar特征分为三类:边缘特征.线性特 ...
- Spring学习总结(19)——Spring概念详解
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建.简单来说,Spring是一个分层的JavaSE/EEfull-stack(一 ...
- static final常量变量的正确书写规范
AccountConstants.java类 命名:常量类以Constants单词命名结尾 package com.paic.pacz.core.salesmanage.util; import ja ...
- HDOJ 5099 Comparison of Android versions 坑题
现场赛的时候错了十四次. . ... Comparison of Android versions Time Limit: 2000/1000 MS (Java/Others) Memory L ...
- python 并发编程入门
多进程 在Unix/Linux下,为我们提供了类似c中<unistd.h>头文件里的的fork()函数的接口,这个函数位于os模块中,相同与c中类似,对于父进程fork()调用返回子进程I ...
- 转:IOS远程推送通知
在ios系统中,app应用程序无法在后台完成较多的任务,仅仅允许程序做一些有限的任务(如音视频播放.地理位置信息.voip).然而,如果你想做 一些有趣的事情,并且告知用户,甚至用户没有使用你的app ...