使用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 ...
随机推荐
- 树(6)-----DFS
1.二叉树的反向层次遍历 def levelOrderBottom1(self, root): res = [] self.dfs(root, 0, res) return res def dfs(s ...
- Codeforces Round #468 (Div. 2, based on Technocup 2018 Final Round)C. Laboratory Work
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some v ...
- LVM man帮助
> man lvm LVM(8) System Manager's Manual LVM(8) NAME lvm — LVM2 tools SYNOPSIS lvm [command|file] ...
- 执行目标文件引发的问题:syntax error: word unexpected (expe...
今天不小心把一个目标文件当成了可执行文件放到开发板上进行执行,结果出现了这样一个问题:./hello_qt: line 1: syntax error: word unexpected (expect ...
- Python-基础-day3
基础数据类型 1.什么是数据类型? 我们人类可以很容易的分清数字与字符的区别,但是计算机并不能呀,计算机虽然很强大,但从某种角度上看又很傻,除非你明确的告诉它,1是数字,“汉”是文字,否则它是分不清1 ...
- XML文件基础
https://c3d.club/xml/basic/2018/12/27/xml-file-base.html 1.文件头 XML文件头有XML声明与DTD文件类型声明组成.其中DTD文件类型声 ...
- IDEA解决中文乱码问题
idea在使用过程中经常会遇到各种乱码问题,网上也有很多解决办法,今天所讲的就是终极解决办法: (1)首先,全局搜索文件 idea64.exe.vmoptions 找到之后,将该行代码复制进去即可 ...
- Spring学习总结(18)——Spring整合Mysql数据库一主多从、多主多从配置
一.新建jdbc.properties配置文件 master.jdbc.driverClassName=com.mysql.jdbc.Driver master.jdbc.url=jdbc:mysql ...
- SQL--各种约束
约束名称 含义 主键约束 定义一个唯一的标识符 外键约束 为了维护和主键表的数据完整性 check约束 限定表中某个列的值的范围 default约束 如果没有指定插入值,则插入默认值 unique约束 ...
- BA--三相异步电机_星三角降压启动
星一三角启动就是一种简单方便的降压启动方式,同时还可通过手动和自动操作控制方式实现. 星三角起动的优点还是很显著的,因为同任何别的减压起动器相比较,其结构最简单,价格也最便宜 除此之外,星三角起动方式 ...