训练了很久的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. 在Windows10中更改”WIN+E“快捷键打开目标

    1> 复制下面代码到记事本保存为launch.vbs 2> 然后打开Regedit.exe并创建以下注册表分支 HKCU:\Software\Classes\CLSID\{52205fd8 ...

  2. node.js 连接 sql server 包括低版本的sqlserver 2000

    利用tedious连接,github地址:https://github.com/tediousjs/tedious 废话不多时直接上代码. connection.js var Connection = ...

  3. [转]地图投影的N种姿势

    此处直接给出原文链接: 1.地图投影的N种姿势 2.GIS理论(墨卡托投影.地理坐标系.地面分辨率.地图比例尺.Bing Maps Tile System)

  4. 总结js基础方法

    //判断对象上是否有个这个属性 hasProreturn obj != null && hasOwnProperty.call(obj, key); //判断是不是布尔值 isBool ...

  5. 【转载】Caffe + Ubuntu 14.04 + CUDA 6.5 新手安装配置指南

    洋洋洒洒一大篇,就没截图了,这几天一直在折腾这个东西,实在没办法,不想用Linux但是,为了Caffe,只能如此了,安装这些东西,遇到很多问题,每个问题都要折磨很久,大概第一次就是这样的.想想,之后应 ...

  6. ArcGIS中的坐标系统定义与投影转换(转)

    ArcGIS中的坐标系统定义与投影转换 ArcGIS中的坐标系统定义与投影转换 坐标系统是GIS数据重要的数学基础,用于表示地理要素.图像和观测结果的参照系统,坐标系统的定义能够保证地理数据在软件中正 ...

  7. mysql/mariadb学习记录——查询2

    Alias——使用一个列名别名AS 关键字: mysql> select sno as studentId,sname as studentName from student; +------- ...

  8. Redis全方位详解--数据类型使用场景和redis分布式锁的正确姿势

    一.Redis数据类型 1.string string是Redis的最基本数据类型,一个key对应一个value,每个value最大可存储512M.string一半用来存图片或者序列化的数据. 2.h ...

  9. PHP分行打印数组-php输出数组方法大全

    我们都知道php有两种方式可以打印数组 $arr = array( "a"=>"orange", "b"=>"bana ...

  10. CMap使用方法总结

    #include <array> #ifdef _DEBUG #include <iostream> #include <fstream> using std::e ...