训练了很久的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文件用在生产环境的更多相关文章

  1. 如何用Tensorflow训练模型成pb文件和和如何加载已经训练好的模型文件

    这篇薄荷主要是讲了如何用tensorflow去训练好一个模型,然后生成相应的pb文件.最后会将如何重新加载这个pb文件. 首先先放出PO主的github: https://github.com/ppp ...

  2. 如何使用tensorboard查看tensorflow  graph****.pb文件的模型结构

    参考网上的:https://github.com/tensorflow/tensorflow/issues/8854 import tensorflow as tf from tensorflow.p ...

  3. 使用tensorflow训练SSD(一):相关环境的配置

    在使用TensorFlow进行目标检测时,首先需要下载tensorflow object detection API模型,该模型的下载地址为https://github.com/tensorflow/ ...

  4. 1 如何使用pb文件保存和恢复模型进行迁移学习(学习Tensorflow 实战google深度学习框架)

    学习过程是Tensorflow 实战google深度学习框架一书的第六章的迁移学习环节. 具体见我提出的问题:https://www.tensorflowers.cn/t/5314 参考https:/ ...

  5. tensorflow学习笔记——模型持久化的原理,将CKPT转为pb文件,使用pb模型预测

    由题目就可以看出,本节内容分为三部分,第一部分就是如何将训练好的模型持久化,并学习模型持久化的原理,第二部分就是如何将CKPT转化为pb文件,第三部分就是如何使用pb模型进行预测. 一,模型持久化 为 ...

  6. tensorflow实战笔记(19)----使用freeze_graph.py将ckpt转为pb文件

    一.作用: https://blog.csdn.net/yjl9122/article/details/78341689 这节是关于tensorflow的Freezing,字面意思是冷冻,可理解为整合 ...

  7. TensorFlow的checkpoint文件转换为pb文件

    由于项目需要,需要将TensorFlow保存的模型从ckpt文件转换为pb文件. import os from tensorflow.python import pywrap_tensorflow f ...

  8. 把ResNet-L152模型的ckpt文件转化为pb文件

    import tensorflow as tf from tensorflow.python.tools import freeze_graph #os.environ['CUDA_VISIBLE_D ...

  9. 将模型.pb文件在tensorboard中展示结构

    本文介绍将训练好的model.pb文件在tensorboard中展示其网络结构. 1. 从pb文件中恢复计算图 import tensorflow as tf model = 'model.pb' # ...

随机推荐

  1. 初识Qt图片显示、平移及旋转

    1.新建一个Qt Gui应用,项目名称为myPicture,基类选择为QMainWindow,类名设置为MainWindow. 2.在mainwindow.h头文件中添加void paintEvent ...

  2. Dom操作(标签--增、删、移动)

    Dom操作 移动或者插入标签的方法 1.append()和appendTo():在现存元素的内部,从后面放入元素: 先声明一个变量用来保存新标签 var $span = $('这是一个span元素') ...

  3. PHP/Laravel轻松上传超大文件

    我们知道,在以前,文件上传采用的是直接传整个文件的方式,这种方式对付一些小文件是没有问题的.而当需要上传大文件时,此种方式不仅操作繁琐,需要修改web服务器和后端语言的配置,而且会大量占用服务器的内存 ...

  4. 【Mac 快捷键】 (不定时持续更新)

    显示/取消显示隐藏文件 command + shift + .

  5. MS522低功耗寻卡

    方案:单片机处于低功耗模式,MS522处于软掉电模式.单片机用RTC定时(比如每隔1s)唤醒,单片机唤醒后唤醒MS522寻卡.寻到卡则做进一步处理,否则MS522继续进入软掉电模式,单片机进入低功耗模 ...

  6. go基础1:Hello world与变量声明

    一.go语言版hello world package main # 指明文件属于main包 main包使用后来定义一个独立的可执行程序,而不是库main包中的main函数是特殊的,不管在什么程序中,m ...

  7. 2017-2018-1 20155232 《信息安全系统设计基础》第十周课堂测试(ch06)补交

    # 2017-2018-1 20155232 <信息安全系统设计基础>第十周课堂测试(ch06)补交 上课时完成测试后在提交的时候,没有提交成功,进行补交. 1.下面代码中,对数组x填充后 ...

  8. 20155308 加分题-mybash的实现(第五周)

    20155308 加分题-mybash的实现(第五周) 实验要求 使用fork,exec,wait实现mybash 写出伪代码,产品代码和测试代码 发表知识理解,实现过程和问题解决的博客(包含代码托管 ...

  9. Maven Java项目添加Scala语言支持

    为了在一个普通的使用Maven构建的Java项目中,增加对Scala语言的支持.使得其能够同时编译Java和Scala语言的文件.其实很简单的一件事情,只需要在pom.xml文件中的build部分中的 ...

  10. cnn 滤波

    http://blog.csdn.net/zouxy09/article/details/49080029