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

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/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/387335.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/387335.shtml
英文地址,請注明出處:http://en.pswp.cn/news/387335.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

簡單的MVC與SQL Server Express LocalDB

M模式&#xff1a; 類&#xff0c;表示數據的應用程序和使用驗證邏輯以強制實施針對這些數據的業務規則。V視圖&#xff1a; 應用程序使用動態生成 HTML 響應的模板文件。C控制器&#xff1a; 處理傳入的瀏覽器請求的類中檢索模型數據&#xff0c;然后指定將響應返回到瀏覽器的…

馬爾可夫鏈 (Markov Chain)是什么鬼

作者&#xff1a;紅猴子鏈接&#xff1a;https://www.zhihu.com/question/26665048/answer/157852228來源&#xff1a;知乎著作權歸作者所有。商業轉載請聯系作者獲得授權&#xff0c;非商業轉載請注明出處。馬爾可夫鏈 &#xff08;Markov Chain&#xff09;是什么鬼 它是隨機…

malloc/free 和 new/delete

(本文參考于網上&#xff09; 首先兩者都可用于申請動態內存和釋放內存&#xff61; 對于非內部數據類型的對象而言&#xff0c;只用malloc/free無法滿足動態對象的要求。對象在創建的同時要自動執行構造函數&#xff0c;對象在消亡之前要自動執行析構函數。由于malloc/free是庫…

主題模型-LDA淺析

個性化推薦、社交網絡、廣告預測等各個領域的workshop上都提到LDA模型&#xff0c;感覺這個模型的應用挺廣泛的&#xff0c;會后抽時間了解了一下LDA&#xff0c;做一下總結&#xff1a; &#xff08;一&#xff09;LDA作用 傳統判斷兩個文檔相似性的方法是通過查看兩個文檔共…

dorado-SplitSpanel控件

1.這是一個界面布局控件 2.分為SideControl邊區域和MainControl主區域 3.常用屬性 3.1 collapsed&#xff1a;打開頁面時&#xff0c;邊區域是否顯示 3.2 position&#xff1a;邊區域占總的大小 轉載于:https://www.cnblogs.com/ergougougou/p/10438752.html

mysql-視圖、事物等

一、視圖 視圖是一個虛擬表&#xff08;非真實存在&#xff09;&#xff0c;其本質是【根據SQL語句獲取動態的數據集&#xff0c;并為其命名】&#xff0c;用戶使用時只需使用【名稱】即可獲取結果集&#xff0c;可以將該結果集當做表來使用。 使用視圖我們可以把查詢過程中的臨…

CAFFE怎樣跑起來

0、參考文獻 [1]caffe官網《Training LeNet on MNIST with Caffe》; [2]薛開宇《讀書筆記4學習搭建自己的網絡MNIST在caffe上進行訓練與學習》&#xff08;[1]的翻譯版&#xff0c;同時還有作者的一些注解&#xff0c;很贊&#xff09;; 1、*.sh文件如何執行&#xff1f; ①方…

運行caffe自帶的兩個簡單例子

為了程序的簡潔&#xff0c;在caffe中是不帶練習數據的&#xff0c;因此需要自己去下載。但在caffe根目錄下的data文件夾里&#xff0c;作者已經為我們編寫好了下載數據的腳本文件&#xff0c;我們只需要聯網&#xff0c;運行這些腳本文件就行了。 注意&#xff1a;在caffe中運…

quartz.net 執行后臺任務

... https://www.cnblogs.com/zhangweizhong/category/771057.html https://www.cnblogs.com/lanxiaoke/category/973331.html 宿主在控制臺程序中 using System;using System.Collections.Specialized;using System.IO;using System.Threading.Tasks;using Quartz;using Quart…

運行caffe自帶的mnist實例詳細教

為了程序的簡潔&#xff0c;在caffe中是不帶練習數據的&#xff0c;因此需要自己去下載。但在caffe根目錄下的data文件夾里&#xff0c;作者已經為我們編寫好了下載數據的腳本文件&#xff0c;我們只需要聯網&#xff0c;運行這些腳本文件就行了。 Mnist介紹&#xff1a;mnist是…

6 軟件的安裝

6 軟件包管理 6.1 簡介 軟件包分類&#xff1a; 源碼包 源代碼&#xff08;大多數是C語言&#xff09; 安裝時慢&#xff0c;容易報錯 >腳本安裝包 對源碼包進行改裝&#xff0c;使安裝更簡單&#xff0c;不多。 rpm包 二進制包 Ubuntu系列的二進制包不是rpm&#xf…

STD函數的內部計算公式

各股票軟件的標準差函數STD是不同的&#xff0c;而布林線的上下軌是以STD為基礎計算出來的&#xff0c;所以使用布林線應小心。以2008/3/28的上證綜指為例&#xff0c;利用如下代碼&#xff1a;"收盤價3日STD:STD(CLOSE,3);"&#xff0c;三日收盤價分別是&#xff1a…

caffe路徑正確,卻讀不到圖片

調試caffe&#xff0c;用已有的網絡訓練自己的數據集的時候&#xff08;我這里做的是二分類&#xff09;。在生成均值文件之后&#xff0c;開始train&#xff0c;發現出現了這個問題。 1&#xff0c;路徑正確&#xff0c;卻讀不到圖片。 [db_lmdb.hpp:15] Check failed: mdb_st…

Eclipse可以執行jsp文件卻無法訪問Tomcat主頁

點擊Servers,然后雙擊本地的Tomcat服務器 出現如下界面 這里要選擇第二項 再重新啟動Tomcat就行了 轉載于:https://www.cnblogs.com/lls1350767625/p/10452565.html

caffe調用的一個例子

本文是學習Caffe官方文檔"ImageNet Tutorial"時做的&#xff0c;同樣由于是Windows版本的原因&#xff0c;很多shell腳本不能直接使用&#xff0c;走了不少彎路&#xff0c;但是收獲也不少。比如&#xff1a;如何讓shell腳本在Windows系統上直接運行、如何去用Caffe給…

孔銅的銅厚

---恢復內容開始--- 表面處理方式注釋&#xff1a; 噴錫 噴錫鉛合金是一種最低成本PCB表面有鉛工藝&#xff0c;它能保持良好的可焊接性。但對于精細引腳間距(<0.64mm)的情況&#xff0c;可能導致焊料的橋接和厚度問題。 無鉛噴錫 一種無鉛表面處理工藝&#xff0c;符合“環…

1 kafka簡介

Publish-subscribe distributed messaging system. A distributed commit log. kafka集群中的服務器都叫broker。 客戶端有兩類&#xff1a;producer、consumer。 客戶端和broker之間使用TCP協議。 不同業務系統的消息通過topic進行區分。 消息的topic會分區&#xff0c;以…

各種機器學習的優缺點及應用場景

目錄 正則化算法&#xff08;Regularization Algorithms&#xff09; 集成算法&#xff08;Ensemble Algorithms&#xff09; 決策樹算法&#xff08;Decision Tree Algorithm&#xff09; 回歸&#xff08;Regression&#xff09; 人工神經網絡&#xff08;Artificial…

微信公眾號接入開發者模式,服務器配置Token驗證

概述 接入微信公眾平臺開發&#xff0c;開發者需要按照如下步驟完成&#xff1a; 填寫服務器配置驗證服務器地址的有效性依據接口文檔實現業務邏輯官方指南文檔服務器配置 服務器地址(URL)&#xff1a;填寫完URL后&#xff0c;微信服務器會發送GET請求&#xff0c;并攜帶以下參…