使用C#把Tensorflow训练的.pb文件用在生产环境
训练了很久的Tf模型,终于要到生产环境中去考研一番了。今天花费了一些时间去研究tf的模型如何在生产环境中去使用。大概整理了这些方法。
继续使用分步骤保存了的ckpt文件
这个貌似脱离不了tensorflow框架,而且生成的ckpt文件比较大,发布到生产环境的时候,还得把python的算法文件一起搞上去,如何和其他程序交互,可能还得自己去写服务。估计很少有人这么做,貌似性能也很一般。
使用tensorflow Serving
tf Serving貌似是大家都比较推崇的方法。需要编译tfServing,然后把模型导出来。直接执行tf Serving的进程,就可以对外提供服务了。具体调用的时候,还得自己写客户端,使用人gRPC去调用Serving,然后再对外提供服务,听上去比较麻烦。而且我今天没太多的时间去研究gRPC,网络上关于客户端很多都是用python写的,我感觉自己的python水平比较菜,没信心能写好。所以这个方式就先没研究。
生产.pb文件,然后写程序去调用.pb文件
生成了.pb文件以后,就可以被程序去直接调用,传入参数,然后就可以传出来参数,而且生成的.pb文件非常的小。而我又有比较丰富的.net开发经验。在想,是否可以用C#来解析.pb文件,然后做一个.net core的对外服务的API,这样貌似更加高效,关键是自己熟悉这款的开发,不用花费太多的时间去摸索。、
具体的思路
使用.net下面的TensorFlow框架tensorflowSharp(貌似还是没脱离了框架).去调用pb文件,然后做成.net core web API 对外提供服务。
具体的实现
直接上代码,非常简单,本身设计到tensorflowsharp的地方非常的少
var graph = new TFGraph();
//重点是下面的这句,把训练好的pb文件给读出来字节,然后导入
var model = File.ReadAllBytes(model_file);
graph.Import(model);
Console.WriteLine("请输入一个图片的地址");
var src = Console.ReadLine();
var tensor = ImageUtil.CreateTensorFromImageFile(src);
using (var sess = new TFSession(graph))
{
var runner = sess.GetRunner();
runner.AddInput(graph["Cast_1"][0], tensor);
var r = runner.Run(graph.softmax(graph["softmax_linear/softmax_linear"][0]));
var v = (float[,])r.GetValue();
Console.WriteLine(v[0,0]);
Console.WriteLine(v[0, 1]);
}
ImageUtil这个类库是tensorflowSharp官方的例子中一个把图片转成tensor的类库,我直接copy过来了,根据我的网络,修改了几个参数。
public static class ImageUtil
{
public static TFTensor CreateTensorFromImageFile(byte[] contents, TFDataType destinationDataType = TFDataType.Float)
{
var tensor = TFTensor.CreateString(contents);
TFOutput input, output;
// Construct a graph to normalize the image
using (var graph = ConstructGraphToNormalizeImage(out input, out output, destinationDataType))
{
// Execute that graph to normalize this one image
using (var session = new TFSession(graph))
{
var normalized = session.Run(
inputs: new[] { input },
inputValues: new[] { tensor },
outputs: new[] { output });
return normalized[0];
}
}
}
// Convert the image in filename to a Tensor suitable as input to the Inception model.
public static TFTensor CreateTensorFromImageFile(string file, TFDataType destinationDataType = TFDataType.Float)
{
var contents = File.ReadAllBytes(file);
// DecodeJpeg uses a scalar String-valued tensor as input.
var tensor = TFTensor.CreateString(contents);
TFOutput input, output;
// Construct a graph to normalize the image
using (var graph = ConstructGraphToNormalizeImage(out input, out output, destinationDataType))
{
// Execute that graph to normalize this one image
using (var session = new TFSession(graph))
{
var normalized = session.Run(
inputs: new[] { input },
inputValues: new[] { tensor },
outputs: new[] { output });
return normalized[0];
}
}
}
// The inception model takes as input the image described by a Tensor in a very
// specific normalized format (a particular image size, shape of the input tensor,
// normalized pixel values etc.).
//
// This function constructs a graph of TensorFlow operations which takes as
// input a JPEG-encoded string and returns a tensor suitable as input to the
// inception model.
private static TFGraph ConstructGraphToNormalizeImage(out TFOutput input, out TFOutput output, TFDataType destinationDataType = TFDataType.Float)
{
// Some constants specific to the pre-trained model at:
// https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
//
// - The model was trained after with images scaled to 224x224 pixels.
// - The colors, represented as R, G, B in 1-byte each were converted to
// float using (value - Mean)/Scale.
const int W = 128;
const int H = 128;
const float Mean = 0;
const float Scale = 1f;
var graph = new TFGraph();
input = graph.Placeholder(TFDataType.String);
output = graph.Cast(
graph.Div(x: graph.Sub(x: graph.ResizeBilinear(images: graph.ExpandDims(input: graph.Cast(graph.DecodeJpeg(contents: input, channels: 3), DstT: TFDataType.Float),
dim: graph.Const(0, "make_batch")),
size: graph.Const(new int[] { W, H }, "size")),
y: graph.Const(Mean, "mean")),
y: graph.Const(Scale, "scale")), destinationDataType);
return graph;
}
}
搞定
使用C#把Tensorflow训练的.pb文件用在生产环境的更多相关文章
- 如何用Tensorflow训练模型成pb文件和和如何加载已经训练好的模型文件
这篇薄荷主要是讲了如何用tensorflow去训练好一个模型,然后生成相应的pb文件.最后会将如何重新加载这个pb文件. 首先先放出PO主的github: https://github.com/ppp ...
- 如何使用tensorboard查看tensorflow graph****.pb文件的模型结构
参考网上的:https://github.com/tensorflow/tensorflow/issues/8854 import tensorflow as tf from tensorflow.p ...
- 使用tensorflow训练SSD(一):相关环境的配置
在使用TensorFlow进行目标检测时,首先需要下载tensorflow object detection API模型,该模型的下载地址为https://github.com/tensorflow/ ...
- 1 如何使用pb文件保存和恢复模型进行迁移学习(学习Tensorflow 实战google深度学习框架)
学习过程是Tensorflow 实战google深度学习框架一书的第六章的迁移学习环节. 具体见我提出的问题:https://www.tensorflowers.cn/t/5314 参考https:/ ...
- tensorflow学习笔记——模型持久化的原理,将CKPT转为pb文件,使用pb模型预测
由题目就可以看出,本节内容分为三部分,第一部分就是如何将训练好的模型持久化,并学习模型持久化的原理,第二部分就是如何将CKPT转化为pb文件,第三部分就是如何使用pb模型进行预测. 一,模型持久化 为 ...
- tensorflow实战笔记(19)----使用freeze_graph.py将ckpt转为pb文件
一.作用: https://blog.csdn.net/yjl9122/article/details/78341689 这节是关于tensorflow的Freezing,字面意思是冷冻,可理解为整合 ...
- TensorFlow的checkpoint文件转换为pb文件
由于项目需要,需要将TensorFlow保存的模型从ckpt文件转换为pb文件. import os from tensorflow.python import pywrap_tensorflow f ...
- 把ResNet-L152模型的ckpt文件转化为pb文件
import tensorflow as tf from tensorflow.python.tools import freeze_graph #os.environ['CUDA_VISIBLE_D ...
- 将模型.pb文件在tensorboard中展示结构
本文介绍将训练好的model.pb文件在tensorboard中展示其网络结构. 1. 从pb文件中恢复计算图 import tensorflow as tf model = 'model.pb' # ...
随机推荐
- 【转】 Android中selector的使用
引言 selector中文的意思选择器,在Android中常常用来作组件的背景,这样做的好处是省去了用代码控制实现组件在不同状态下不同的背景颜色或图片的变换.使用十分方便. selector的定义 s ...
- Hadoop学习之路(十二)分布式集群中HDFS系统的各种角色
NameNode 学习目标 理解 namenode 的工作机制尤其是元数据管理机制,以增强对 HDFS 工作原理的 理解,及培养 hadoop 集群运营中“性能调优”.“namenode”故障问题的分 ...
- webpack.config.js配置遇到Error: Cannot find module '@babel/core'问题
在webpack配置,将ES6转成ES5的时候,,出现Error: Cannot find module '@babel/core'错误最初以为是babel-core没有安装上.重装了好几遍babel ...
- 集合之保持compareTo和equals同步
在Java中我们常使用Comparable接口来实现排序,其中compareTo是实现该接口方法.我们知道compareTo返回0表示两个对象相等,返回正数表示大于,返回负数表示小于.同时我们也知道e ...
- java中抽象的(abstract)方法是否可同时是静态的(static),是否可同时是本地方法(native),是否可同时被synchronized修饰
1.abstract与static what abstract:用来声明抽象方法,抽象方法没有方法体,不能被直接调用,必须在子类overriding后才能使用. static:用来声明静态方法,静态方 ...
- mapent
package test12; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import ja ...
- Spring源码分析(二十)准备环境
摘要: 本文结合<Spring源码深度解析>来分析Spring 5.0.6版本的源代码.若有描述错误之处,欢迎指正. prepareRefresh函数主要是做些准备工作,例如对系统属性及环 ...
- highcharts柱状图实现legend和数据列一一对应效果
var cate = ['Green', 'Pink']; Highcharts.chart('container', { chart: { type: 'column' }, legend: { e ...
- 06_Java基础语法_第6天(自定义类、ArrayList集合)_讲义
今日内容介绍 1.自定义类型的定义及使用 2.自定义类的内存图 3.ArrayList集合的基本功能 4.随机点名器案例及库存案例代码优化 01引用数据类型_类 * A: 数据类型 * a: java ...
- Spring第三天——AOP注解实现与事务管理
大致内容: aspectJ的aop操作(基于注解,对比day02配置操作)(会用) *jdbcTemplate操作(实现CRUD) *spring配置连接池 *spring事务管理 一.AspectJ ...