TensorFlowSharp入門使用C#編寫TensorFlow人工智能應用

TensorFlowSharp入門使用C#編寫TensorFlow人工智能應用學習。

TensorFlow簡單介紹

TensorFlow 是谷歌的第二代機器學習系統,按照谷歌所說,在某些基準測試中,TensorFlow的表現比第一代的DistBelief快了2倍。

TensorFlow 內建深度學習的擴展支持,任何能夠用計算流圖形來表達的計算,都可以使用TensorFlow。任何基於梯度的機器學習算法都能夠受益於TensorFlow的自動分化(auto-differentiation)。通過靈活的Python接口,要在TensorFlow中表達想法也會很容易。

TensorFlow 對於實際的產品也是很有意義的。將思路從桌面GPU訓練無縫搬遷到手機中運行。

示例Python代碼:

複製代碼

import tensorflow as tfimport numpy as np# Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3x_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# p_w_picpath recognition

圖像識別示例體驗

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

下面學習一個實際的人工智能應用,是非常簡單的一個示例,圖像識別。

新建一個 p_w_picpathrecognition .NET Framework 控制檯應用項目,接着添加TensorFlowSharp 引用。

然後在項目屬性中生成->平臺目標 改爲 x64

接着編寫如下代碼:

 

 View Code

這裏需要注意的是由於需要下載初始Graph和標籤,而且是google的站點,所以得使用一些特殊手段。

最終我隨便下載了幾張圖放到bin\Debug\img

 

 然後運行程序,首先確保bin\Debug\tmp文件夾下有tensorflow_inception_graph.pb及p_w_picpathnet_comp_graph_label_strings.txt。

 

人工智能的魅力非常大,本文只是一個入門,複製上面的代碼,你沒法訓練模型等等操作。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章