使用C#编写TensorFlow人工智能应用

1,671 阅读3分钟

 

TensorFlow简单介绍

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

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

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

示例Python代码:

复制代码

  1. import tensorflow as tf
  2. import numpy as np
  3. # Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
  4. x_data = np.random.rand(100).astype(np.float32)
  5. y_data = x_data * 0.1 + 0.3
  6. # Try to find values for W and b that compute y_data = W * x_data + b
  7. # (We know that W should be 0.1 and b 0.3, but TensorFlow will
  8. # figure that out for us.)
  9. W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
  10. b = tf.Variable(tf.zeros([1]))
  11. y = W * x_data + b
  12. # Minimize the mean squared errors.
  13. loss = tf.reduce_mean(tf.square(y - y_data))
  14. optimizer = tf.train.GradientDescentOptimizer(0.5)
  15. train = optimizer.minimize(loss)
  16. # Before starting, initialize the variables. We will 'run' this first.
  17. init = tf.global_variables_initializer()
  18. # Launch the graph.
  19. sess = tf.Session()
  20. sess.run(init)
  21. # Fit the line.
  22. for step in range(201):
  23. sess.run(train)
  24. if step % 20 == 0:
  25. print(step, sess.run(W), sess.run(b))
  26. # 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 写入如下代码:

复制代码

  1. static void Main(string[] args)
  2. {
  3. using (var session = new TFSession())
  4. {
  5. var graph = session.Graph;
  6. Console.WriteLine(TFCore.Version);
  7. var a = graph.Const(2);
  8. var b = graph.Const(3);
  9. Console.WriteLine("a=2 b=3");
  10. // 两常量加
  11. var addingResults = session.GetRunner().Run(graph.Add(a, b));
  12. var addingResultValue = addingResults[0].GetValue();
  13. Console.WriteLine("a+b={0}", addingResultValue);
  14. // 两常量乘
  15. var multiplyResults = session.GetRunner().Run(graph.Mul(a, b));
  16. var multiplyResultValue = multiplyResults[0].GetValue();
  17. Console.WriteLine("a*b={0}", multiplyResultValue);
  18. var tft = new TFTensor(Encoding.UTF8.GetBytes($"Hello TensorFlow Version {TFCore.Version}! LineZero"));
  19. var hello = graph.Const(tft);
  20. var helloResults = session.GetRunner().Run(hello);
  21. Console.WriteLine(Encoding.UTF8.GetString((byte[])helloResults[0].GetValue()));
  22. }
  23. Console.ReadKey();
  24. }

复制代码

运行程序结果如下:

 

TensorFlow C# image recognition

图像识别示例体验

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

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

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

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

接着编写如下代码:

 

 View Code

这里需要注意的是由于需要下载初始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/