TensorFlowSharp入门使用C#编写TensorFlow人工智能应用学习。

TensorFlow简单介绍

TensorFlow 是谷歌的第二代机器学习系统,按照谷歌所说,在某些基准测试中,TensorFlow的表现比第一代的DistBelief快了2倍。

TensorFlow 内建深度学习的扩展支持,任何能够用计算流图形来表达的计算,都可以使用TensorFlow。任何基于梯度的机器学习算法都能够受益于TensorFlow的自动分化(auto-differentiation)。通过灵活的Python接口,要在TensorFlow中表达想法也会很容易。

TensorFlow 对于实际的产品也是很有意义的。将思路从桌面GPU训练无缝搬迁到手机中运行。

示例Python代码:

import tensorflow as tf
import numpy as np# Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3# Try to find values for W and b that compute y_data = W * x_data + b
# (We know that W should be 0.1 and b 0.3, but TensorFlow will
# figure that out for us.)
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b# Minimize the mean squared errors.
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)# Before starting, initialize the variables.  We will 'run' this first.
init = tf.global_variables_initializer()# Launch the graph.
sess = tf.Session()
sess.run(init)# Fit the line.
for step in range(201):sess.run(train)if step % 20 == 0:print(step, sess.run(W), sess.run(b))# Learns best fit is W: [0.1], b: [0.3]

使用TensorFlowSharp

GitHub:https://github.com/migueldeicaza/TensorFlowSharp

官方源码库,该项目支持跨平台,使用Mono。

可以使用NuGet 安装TensorFlowSharp,如下:

Install-Package TensorFlowSharp

编写简单应用

使用VS2017新建一个.NET Framework 控制台应用 tensorflowdemo,接着添加TensorFlowSharp 引用。

TensorFlowSharp 包比较大,需要耐心等待。

然后在项目属性中生成->平台目标 改为 x64。

打开Program.cs 写入如下代码:

        static void Main(string[] args){using (var session = new TFSession()){var graph = session.Graph;Console.WriteLine(TFCore.Version);var a = graph.Const(2);var b = graph.Const(3);Console.WriteLine("a=2 b=3");// 两常量加var addingResults = session.GetRunner().Run(graph.Add(a, b));var addingResultValue = addingResults[0].GetValue();Console.WriteLine("a+b={0}", addingResultValue);// 两常量乘var multiplyResults = session.GetRunner().Run(graph.Mul(a, b));var multiplyResultValue = multiplyResults[0].GetValue();Console.WriteLine("a*b={0}", multiplyResultValue);var tft = new TFTensor(Encoding.UTF8.GetBytes($"Hello TensorFlow Version {TFCore.Version}! LineZero"));var hello = graph.Const(tft);var helloResults = session.GetRunner().Run(hello);Console.WriteLine(Encoding.UTF8.GetString((byte[])helloResults[0].GetValue()));}Console.ReadKey();}        

运行程序结果如下:

TensorFlow C# image recognition

图像识别示例体验

https://github.com/migueldeicaza/TensorFlowSharp/tree/master/Examples/ExampleInceptionInference

下面学习一个实际的人工智能应用,是非常简单的一个示例,图像识别。

新建一个 imagerecognition .NET Framework 控制台应用项目,接着添加TensorFlowSharp 引用。

然后在项目属性中生成->平台目标 改为 x64。

接着编写如下代码:

    class Program{static string dir, modelFile, labelsFile;public static void Main(string[] args){dir = "tmp";List<string> files = Directory.GetFiles("img").ToList();ModelFiles(dir);var graph = new TFGraph();// 从文件加载序列化的GraphDefvar model = File.ReadAllBytes(modelFile);//导入GraphDefgraph.Import(model, "");using (var session = new TFSession(graph)){var labels = File.ReadAllLines(labelsFile);Console.WriteLine("TensorFlow图像识别 LineZero");foreach (var file in files){// Run inference on the image files// For multiple images, session.Run() can be called in a loop (and// concurrently). Alternatively, images can be batched since the model// accepts batches of image data as input.var tensor = CreateTensorFromImageFile(file);var runner = session.GetRunner();runner.AddInput(graph["input"][0], tensor).Fetch(graph["output"][0]);var output = runner.Run();// output[0].Value() is a vector containing probabilities of// labels for each image in the "batch". The batch size was 1.// Find the most probably label index.var result = output[0];var rshape = result.Shape;if (result.NumDims != 2 || rshape[0] != 1){var shape = "";foreach (var d in rshape){shape += $"{d} ";}shape = shape.Trim();Console.WriteLine($"Error: expected to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape [{shape}]");Environment.Exit(1);}// You can get the data in two ways, as a multi-dimensional array, or arrays of arrays, // code can be nicer to read with one or the other, pick it based on how you want to process// itbool jagged = true;var bestIdx = 0;float p = 0, best = 0;if (jagged){var probabilities = ((float[][])result.GetValue(jagged: true))[0];for (int i = 0; i < probabilities.Length; i++){if (probabilities[i] > best){bestIdx = i;best = probabilities[i];}}}else{var val = (float[,])result.GetValue(jagged: false);// Result is [1,N], flatten arrayfor (int i = 0; i < val.GetLength(1); i++){if (val[0, i] > best){bestIdx = i;best = val[0, i];}}}Console.WriteLine($"{Path.GetFileName(file)} 最佳匹配: [{bestIdx}] {best * 100.0}% 标识为:{labels[bestIdx]}");}}Console.ReadKey();}// Convert the image in filename to a Tensor suitable as input to the Inception model.static TFTensor CreateTensorFromImageFile(string file){var contents = File.ReadAllBytes(file);// DecodeJpeg uses a scalar String-valued tensor as input.var tensor = TFTensor.CreateString(contents);TFGraph graph;TFOutput input, output;// Construct a graph to normalize the imageConstructGraphToNormalizeImage(out graph, out input, out output);// Execute that graph to normalize this one imageusing (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.static void ConstructGraphToNormalizeImage(out TFGraph graph, out TFOutput input, out TFOutput output){// 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 = 224;const int H = 224;const float Mean = 117;const float Scale = 1;graph = new TFGraph();input = graph.Placeholder(TFDataType.String);output = 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"));}/// <summary>/// 下载初始Graph和标签/// </summary>/// <param name="dir"></param>static void ModelFiles(string dir){string url = "https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip";modelFile = Path.Combine(dir, "tensorflow_inception_graph.pb");labelsFile = Path.Combine(dir, "imagenet_comp_graph_label_strings.txt");var zipfile = Path.Combine(dir, "inception5h.zip");if (File.Exists(modelFile) && File.Exists(labelsFile))return;Directory.CreateDirectory(dir);var wc = new WebClient();wc.DownloadFile(url, zipfile);ZipFile.ExtractToDirectory(zipfile, dir);File.Delete(zipfile);}}

这里需要注意的是由于需要下载初始Graph和标签,而且是google的站点,所以得使用一些特殊手段。

最终我随便下载了几张图放到bin\Debug\img

然后运行程序,首先确保bin\Debug\tmp文件夹下有tensorflow_inception_graph.pb及imagenet_comp_graph_label_strings.txt。

人工智能的魅力非常大,本文只是一个入门,复制上面的代码,你没法训练模型等等操作。所以道路还是很远,需一步一步来。

更多可以查看 https://github.com/migueldeicaza/TensorFlowSharp 及 https://github.com/tensorflow/models

参考文档:

TensorFlow 官网:https://www.tensorflow.org/get_started/

TensorFlow 中文社区:http://www.tensorfly.cn/

TensorFlow 官方文档中文版:http://wiki.jikexueyuan.com/project/tensorflow-zh/

C#编写TensorFlow人工智能应用 TensorFlowSharp相关推荐

  1. TensorFlowSharp入门使用C#编写TensorFlow人工智能应用

    TensorFlowSharp入门使用C#编写TensorFlow人工智能应用学习. TensorFlow简单介绍 TensorFlow 是谷歌的第二代机器学习系统,按照谷歌所说,在某些基准测试中,T ...

  2. [转]在C#中像Python一样编写TensorFlow机器学习代码

    机器学习是一个令人激动人心的领域,一直有新的技术突破.研究人员不断推动机器智能的提升,教机器如何听说读写--这些曾经是我们人类专属的技能.机器学习的首选语言是Python,最受欢迎的库是Google的 ...

  3. 02基于python玩转人工智能最火框架之TensorFlow人工智能深度学习介绍

    人工智能之父麦卡锡给出的定义 构建智能机器,特别是智能计算机程序的科学和工程. 人工智能是一种让计算机程序能够"智能地"思考的方式 思考的模式类似于人类. 什么是智能? 智能的英语 ...

  4. TensorFlow人工智能入门教程之十一 最强网络DLSTM 双向长短期记忆网络(阿里小AI实现)...

    2019独角兽企业重金招聘Python工程师标准>>> 失眠 ....上一章 讲了 最强网络之一 RSNN 深度残差网络 这一章节 我们来讲讲  还有一个很强的网络模型,就是双向LS ...

  5. python 青少年人工智能_青少年人工智能教育的典范 优必学教孩子用Python编写一部人工智能的字典...

    Python是一种计算机程序设计语言,是一种动态的.面向对象的脚本语言,最初被设计用于编写自动化脚本.从20世纪90年代初诞生至今,Python正在迅速成为全球大中小学编程入门课程的首选教学语言,这种 ...

  6. tensorflow人工智能-卫星图像识别

    介绍 机器学习,人工智能,深度学习作业项目.卫星图像识别系统.基于tensorflow,使用卷积神经网络实现对卫星影像(飞机,湖泊)的识别,通过对相关数据集的训练(1400张影像图片)生成训练模型,使 ...

  7. TensorFlow人工智能引擎入门教程之二 CNN卷积神经网络的基本定义理解。

    摘要: 这一章节我们将 tensorFlow怎么实现卷积神经网络 ,CNN ,其实CNN可以用来训练声音的,不过效果一般,所以一般都用于图像方面,因为图像像素局部共享 参数共享 ,图像金字塔法则.可以 ...

  8. TensorFlow人工智能引擎入门教程之十 最强网络 RSNN深度残差网络 平均准确率96-99%

    摘要: 这一章节我们讲一下 RSNN深度残差网络 ,他准确率非常好,比CNN还要高.而且非常新 出现在2015 residual network http://blog.csdn.net/sunbai ...

  9. 资源类❀超实用学术必备的论文学习网站和英文论文编写,人工智能学习网站(免费)

    目录 前言Intr 1.文献查找和下载 1.1.papers with code(论文和代码) 1.2.Research rabbit(研究兔) 1.3.Google 学术 2.论文AI总结 3.文献 ...

最新文章

  1. python中内建函数isinstance的用法
  2. ubuntu mysql 内存满了_ubuntu – 如何为mySQL分配内存限制?
  3. Ubuntu安装deb软件包错误(依赖关系问题)解决
  4. 开发技巧-使用SQL与Navicat快速导出一个自定义的MYSQL数据库字段表格(数据字典)为Word或Excel
  5. 【IntelliJ】IntelliJ IDEA常用设置及快捷键以及自定义Live templates
  6. mysql 触发器 注意事项_MySQL触发器的利弊-使用MySQL触发器时应该注意的事项
  7. java编程思想第四版第十四章 类型信息习题
  8. 数据卡片_VISA消息:关于VCPS 2.1卡片产品的性能和交叉测试的卡片个性化数据的更新...
  9. 纯CSS菜单样式,及其Shadow DOM,Json接口 实现
  10. mybatis-plus对datetime返回去掉.0_0欧姆电阻到底有没有用?这12个作用说明其不可或缺...
  11. android 平板键盘布局,7款Android平板输入法横向评测,安卓平板软件HD/THD下载
  12. cisco2811 路由器修改密码
  13. ASCII表,二进制、十进制对照表
  14. 用计算机画图评课稿,小学信息技术三年级下册《图形的复制与粘贴》说课稿
  15. 进程上下文切换 – 残酷的性能杀手(上)
  16. android开发--mp3播放器项目源代码(xml文件解析,.lrc,.mp3文件下载,同时显示歌词)
  17. 将txt文件批量转换成pdf格式的方法
  18. 数字集成电路设计(五、仿真验证与 Testbench 编写)(一)
  19. egg使用egg-socket.io
  20. Day65:Python获取阿里云产品云监控数据指标

热门文章

  1. 编写计算表达式(X-Y+25)/Z的值得程序,要求将其商和余数分别放在A、B单元中。(设X和Y是32位无符号数,A、B和Z是16位无符号数,不考虑溢出情况。)
  2. Java——集合(Map集合的两种迭代)
  3. python安全攻防---信息收集---IP查询
  4. mysql 关联查询_Mysql查询优化器,再也不会因为该什么时候建立索引发愁了
  5. 设计师必备的html工具
  6. linux操作系统进程间通信IPC之管道pipe及FIFO
  7. 没写client,想先测试server端怎么办?
  8. TCP协议-如何保证传输可靠性
  9. 用strace工具跟踪系统调用
  10. 【计算机系统设计】重点 · 学习笔记(0)