C#編寫TensorFlow人工智能應用


C#編寫TensorFlow人工智能應用

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

接着編寫如下代碼:

 

  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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM