.NET 幫助

TensorFlow .NET(它對開發者的運作方式)

Chipego
奇佩戈·卡林达
2024年7月1日
分享:

機器學習(ML)透過促進智能決策和自動化,已經在從醫療保健到金融等各行各業帶來了革命性的變革。 TensorFlow,Google 的開源機器學習和深度學習框架,一直在這場革命的前沿。 使用TensorFlow.NET,.NET開發人員可以在C#生態系統中利用TensorFlow的強大功能。 在本文中,我們將探討TensorFlow.NET,其特性、優勢以及在 C# 開發中的實際應用。 此外,我們將學習名為IronPDF的PDF生成庫,來自Iron Software,並提供一個實際範例。

了解 TensorFlow.NET

TensorFlow.NET 是 TensorFlow 的 .NET 綁定,允許開發人員直接在 C# 和 .NET 應用層中使用 TensorFlow 功能。 由社群開發並由 SciSharp 組織維護,TensorFlow.NET 提供 TensorFlow 的機器學習和神經網絡功能與 .NET 平台的多功能性無縫集成。 它使 C# 開發人員可以建立神經網路、訓練模型或訓練圖像,並使用 TensorFlow 的廣泛系統 API 和工具部署機器學習模型。

TensorFlow.NET 的主要功能

  1. TensorFlow 兼容性TensorFlow.NET 提供與 TensorFlow 的 API 和操作的全面兼容,包括張量操作或激活、神經網絡層、損失函數、優化器以及用於數據預處理和評估的工具。

  2. 高性能TensorFlow.NET 利用 TensorFlow 的高效計算圖形執行引擎和優化的內核,在 CPU 和 GPU 上提供高性能的機器學習推理和訓練。

  3. 輕鬆整合TensorFlow.NET能夠與現有的 .NET 應用程式和庫無縫整合,使開發者能在熟悉的 C# 開發環境中運用 TensorFlow 的功能。

  4. 模型可攜性TensorFlow.NET 允許開發者導入預先訓練的 TensorFlow 模型,並導出訓練後的模型,以在其他基於 TensorFlow 的環境(如 Python 或移動設備)中進行推理。

  5. 靈活性和可擴展性TensorFlow.NET 提供了使用 C# 語言特性來自定義和擴展機器學習模型的靈活性,例如用於數據操作的 LINQ(語言集成查詢)和用於模型組合的函數式編程範式。

  6. 社群支援與文件TensorFlow.NET從活躍的貢獻者社群中受益,這些貢獻者提供文件、教程和範例,幫助開發者在C#世界中使用TensorFlow開始機器學習。

使用 TensorFlow.NET 的實用範例

讓我們來探索一些實際情境,看看如何使用TensorFlow.NET來在C#中構建和部署機器學習模型:

  1. 載入和使用預訓練模型
    // Load a pre-trained TensorFlow model
    var model = TensorFlowModel.LoadModel("model.pb");
    // Perform inference on input data
    var input = new float[,] { { 1.0f, 2.0f, 3.0f } };
    var output = model.Predict(input);
    // Load a pre-trained TensorFlow model
    var model = TensorFlowModel.LoadModel("model.pb");
    // Perform inference on input data
    var input = new float[,] { { 1.0f, 2.0f, 3.0f } };
    var output = model.Predict(input);
' Load a pre-trained TensorFlow model
	Dim model = TensorFlowModel.LoadModel("model.pb")
	' Perform inference on input data
	Dim input = New Single(, ) {
		{ 1.0F, 2.0F, 3.0F }
	}
	Dim output = model.Predict(input)
$vbLabelText   $csharpLabel
  1. 訓練自訂模型
    // Create a neural network model using TensorFlow.NET APIs and metrics
    var input = new Input(Shape.Scalar);
    var output = new Dense(1, Activation.ReLU).Forward(input);
    // Compile the model with loss function and optimizer algorithms
    var model = new Model(input, output);
    model.Compile(optimizer: new SGD(), loss: Losses.MeanSquaredError);
    // Train the model with training data just like Python
    model.Fit(x_train, y_train, epochs: 10, batchSize: 32);
    // Create a neural network model using TensorFlow.NET APIs and metrics
    var input = new Input(Shape.Scalar);
    var output = new Dense(1, Activation.ReLU).Forward(input);
    // Compile the model with loss function and optimizer algorithms
    var model = new Model(input, output);
    model.Compile(optimizer: new SGD(), loss: Losses.MeanSquaredError);
    // Train the model with training data just like Python
    model.Fit(x_train, y_train, epochs: 10, batchSize: 32);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel
  1. 評估與部署
    // Evaluate the trained model on test data
    var evaluation = model.Evaluate(x_test, y_test);
    // Export the trained model for deployment
    model.SaveModel("trained_model.pb");
    // Evaluate the trained model on test data
    var evaluation = model.Evaluate(x_test, y_test);
    // Export the trained model for deployment
    model.SaveModel("trained_model.pb");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

有關 TensorFlow 的更多範例可以在TensorFlow.NET 範例頁面找到。

// static Tensorflow
using static Tensorflow.Binding;
namespace IronPdfDemos
{
    public class TensorFlow
    {
        public static void Execute()
        {
            var hello = tf.constant("Hello, TensorFlow!");
            Console.WriteLine(hello);
        }
    }
}
// static Tensorflow
using static Tensorflow.Binding;
namespace IronPdfDemos
{
    public class TensorFlow
    {
        public static void Execute()
        {
            var hello = tf.constant("Hello, TensorFlow!");
            Console.WriteLine(hello);
        }
    }
}
' static Tensorflow
Imports Tensorflow.Binding
Namespace IronPdfDemos
	Public Class TensorFlow
		Public Shared Sub Execute()
			Dim hello = tf.constant("Hello, TensorFlow!")
			Console.WriteLine(hello)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

範例 Hello TensorFlow 輸出

TensorFlow .NET(對開發者的運作方式):圖 1 - 控制台應用程式輸出

使用 TensorFlow.NET 的優勢

  1. 無縫整合TensorFlow.NET 將 TensorFlow 的強大功能帶入 .NET 生態系統,使 C# 開發人員能夠在其應用程序中利用最先進的機器學習技術和算法。

  2. 效能與擴展性TensorFlow.NET 利用 TensorFlow 的執行優化引擎來提供高效能的機器學習計算,使其適合處理大規模數據集、測試圖像以及複雜或稠密的模型。

  3. 熟悉的開發環境TensorFlow.NET API 允許開發者使用熟悉的 C# 語言特性和開發工具來建構和部署機器學習模型,從而降低在 C# 應用程式中採用機器學習的學習曲線。

  4. 互操作性和可移植性TensorFlow.NET促進與其他基於TensorFlow的環境的互操作性,使基於C#的機器學習模型能夠與Python、TensorFlow Serving和TensorFlow Lite無縫整合。

  5. 社群驅動的開發TensorFlow.NET得益於活躍的貢獻者和用戶社群,他們提供支援、反饋和對專案的貢獻,確保其持續成長和改進。

TensorFlow.NET 授權

這是一個開源的 Apache 授權套件,可以免費使用。 更多關於許可證的信息可以在TensorFlow.NET 許可證頁面上閱讀。

介紹 IronPDF

TensorFlow .NET(開發者如何使用):圖2 - IronPDF

IronPDF 是一個強大的 C# PDF 庫,允許開發人員直接從 HTML、CSS、圖像和 JavaScript 輸入創建、編輯和簽署 PDF。 這是一個商業級解決方案,具有高性能和低內存佔用。 以下是一些主要功能:

  1. HTML 到 PDF 轉換IronPDF 可以將 HTML 文件、HTML 字串和 URL 轉換為 PDF。 例如,您可以使用 Chrome PDF 渲染器將網頁渲染為 PDF。

  2. 跨平台支援IronPDF 支援多種 .NET 平台,包括 .NET Core、.NET Standard 和 .NET Framework。 它兼容 Windows、Linux 和 macOS。

  3. 编辑和签署:您可以设置属性,添加安全性(密码和权限),甚至对 PDF 文件应用数字签名。

  4. 頁面模板和設定:自訂您的 PDF,添加頁眉、頁腳和頁碼,並調整邊距。 IronPDF 也支持響應式佈局和自定義紙張尺寸。

  5. 標準合規IronPDF 遵循 PDF/A 和 PDF/UA 等 PDF 標準。 它支持 UTF-8 字符編碼並處理圖像、CSS 和字體等資產。

使用 TensorFlow.NET 和 IronPDF 生成 PDF 文件

首先,創建一個 Visual Studio 專案並選擇下面的控制台應用程式模板。

TensorFlow .NET(它如何為開發人員工作):圖3 - Visual Studio 專案

提供專案名稱和位置。

TensorFlow .NET(對開發者的運作方式):圖4 - 專案配置

在下一步選擇所需的 .NET 版本,然後點擊“建立”按鈕。

從 Visual Studio 套件管理員的 NuGet 套件安裝 IronPDF

TensorFlow .NET (它對開發人員的作用):圖5 - TensorFlow.NET

安裝套件TensorFlow.NETTensorFlow.Keras,這是一個獨立的套件,用於運行模型。

TensorFlow .NET(開發人員如何使用):圖 6 - 安裝套件 TensorFlow.Keras

using IronPdf;
using static Tensorflow.Binding;

namespace IronPdfDemos
{
    public class Program
    {
        public static void Main()
        {
            // Instantiate Cache and ChromePdfRenderer
            var renderer = new ChromePdfRenderer();

            // Prepare HTML
            var content = "<h1>Demonstrate TensorFlow with IronPDF</h1>";
            content += $"<p></p>";
            content += $"<h2></h2>";

            // Eager mode
            content += $"<h2>Enable Eager Execution</h2>";
            content += $"<p>tf.enable_eager_execution();</p>";

            // tf is a static TensorFlow instance
            tf.enable_eager_execution(); // Enable eager mode

            content += $"<h2>Define tensor constants.</h2>";
            // Introduce tensor constants
            var a = tf.constant(5);
            var b = tf.constant(6);
            var c = tf.constant(7);

            content += $"<p></p>";
            content += $"<p></p>";
            content += $"<p></p>";

            content += $"<h2>Various tensor operations.</h2>";
            // Various tensor operations usage
            // Note: Tensors also support operators (+, *, ...)
            var add = tf.add(a, b);
            var sub = tf.subtract(a, b);
            var mul = tf.multiply(a, b);
            var div = tf.divide(a, b);

            content += $"<p>var add = tf.add(a, b);</p>";
            content += $"<p>var sub = tf.subtract(a, b);</p>";
            content += $"<p>var mul = tf.multiply(a, b);</p>";
            content += $"<p>var div = tf.divide(a, b);</p>";

            content += $"<h2>Access tensors value.</h2>";
            // Tensors value
            print($"{(int)a} + {(int)b} = {(int)add}");
            print($"{(int)a} - {(int)b} = {(int)sub}");
            print($"{(int)a} * {(int)b} = {(int)mul}");
            print($"{(int)a} / {(int)b} = {(double)div}");

            content += $"<p>{(int)a} + {(int)b} = {(int)add}</p>";
            content += $"<p>{(int)a} - {(int)b} = {(int)sub}</p>";
            content += $"<p>{(int)a} * {(int)b} = {(int)mul}</p>";
            content += $"<p>{(int)a} / {(int)b} = {(double)div}</p>";

            // Some more operations
            var mean = tf.reduce_mean(tf.constant(new[] { a, b, c }));
            var sum = tf.reduce_sum(tf.constant(new[] { a, b, c }));

            content += $"<h2>Access tensors value.</h2>";
            // Access tensors value
            print("mean =", mean.numpy());
            print("sum =", sum.numpy());

            content += $"<p>mean = {mean.numpy()}</p>";
            content += $"<p>sum = {sum.numpy()}</p>";

            content += $"<h2>Matrix multiplications.</h2>";
            // Matrix multiplications with a single row
            var matrix1 = tf.constant(new float[,] { { 1, 2 }, { 3, 4 } });
            var matrix2 = tf.constant(new float[,] { { 5, 6 }, { 7, 8 } });
            var product = tf.matmul(matrix1, matrix2);

            content += "<p>matrix1 = tf.constant(new float[,] { { { 1, 2 }}, { { 3, 4 }} })</p>";
            content += "<p>matrix2 = tf.constant(new float[,] { { { 5, 6 }}, { { 7, 8 }} })</p>";
            content += "<p>product = tf.matmul(matrix1, matrix2)</p>";

            content += $"<h2>Convert Tensor to Numpy.</h2>";
            // Convert Tensor to Numpy
            print("product =", product.numpy());

            content += $"<p>product = {product.numpy()}</p>";

            // Create a PDF from an HTML string using C#
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("tensorflow.pdf");
        }
    }
}
using IronPdf;
using static Tensorflow.Binding;

namespace IronPdfDemos
{
    public class Program
    {
        public static void Main()
        {
            // Instantiate Cache and ChromePdfRenderer
            var renderer = new ChromePdfRenderer();

            // Prepare HTML
            var content = "<h1>Demonstrate TensorFlow with IronPDF</h1>";
            content += $"<p></p>";
            content += $"<h2></h2>";

            // Eager mode
            content += $"<h2>Enable Eager Execution</h2>";
            content += $"<p>tf.enable_eager_execution();</p>";

            // tf is a static TensorFlow instance
            tf.enable_eager_execution(); // Enable eager mode

            content += $"<h2>Define tensor constants.</h2>";
            // Introduce tensor constants
            var a = tf.constant(5);
            var b = tf.constant(6);
            var c = tf.constant(7);

            content += $"<p></p>";
            content += $"<p></p>";
            content += $"<p></p>";

            content += $"<h2>Various tensor operations.</h2>";
            // Various tensor operations usage
            // Note: Tensors also support operators (+, *, ...)
            var add = tf.add(a, b);
            var sub = tf.subtract(a, b);
            var mul = tf.multiply(a, b);
            var div = tf.divide(a, b);

            content += $"<p>var add = tf.add(a, b);</p>";
            content += $"<p>var sub = tf.subtract(a, b);</p>";
            content += $"<p>var mul = tf.multiply(a, b);</p>";
            content += $"<p>var div = tf.divide(a, b);</p>";

            content += $"<h2>Access tensors value.</h2>";
            // Tensors value
            print($"{(int)a} + {(int)b} = {(int)add}");
            print($"{(int)a} - {(int)b} = {(int)sub}");
            print($"{(int)a} * {(int)b} = {(int)mul}");
            print($"{(int)a} / {(int)b} = {(double)div}");

            content += $"<p>{(int)a} + {(int)b} = {(int)add}</p>";
            content += $"<p>{(int)a} - {(int)b} = {(int)sub}</p>";
            content += $"<p>{(int)a} * {(int)b} = {(int)mul}</p>";
            content += $"<p>{(int)a} / {(int)b} = {(double)div}</p>";

            // Some more operations
            var mean = tf.reduce_mean(tf.constant(new[] { a, b, c }));
            var sum = tf.reduce_sum(tf.constant(new[] { a, b, c }));

            content += $"<h2>Access tensors value.</h2>";
            // Access tensors value
            print("mean =", mean.numpy());
            print("sum =", sum.numpy());

            content += $"<p>mean = {mean.numpy()}</p>";
            content += $"<p>sum = {sum.numpy()}</p>";

            content += $"<h2>Matrix multiplications.</h2>";
            // Matrix multiplications with a single row
            var matrix1 = tf.constant(new float[,] { { 1, 2 }, { 3, 4 } });
            var matrix2 = tf.constant(new float[,] { { 5, 6 }, { 7, 8 } });
            var product = tf.matmul(matrix1, matrix2);

            content += "<p>matrix1 = tf.constant(new float[,] { { { 1, 2 }}, { { 3, 4 }} })</p>";
            content += "<p>matrix2 = tf.constant(new float[,] { { { 5, 6 }}, { { 7, 8 }} })</p>";
            content += "<p>product = tf.matmul(matrix1, matrix2)</p>";

            content += $"<h2>Convert Tensor to Numpy.</h2>";
            // Convert Tensor to Numpy
            print("product =", product.numpy());

            content += $"<p>product = {product.numpy()}</p>";

            // Create a PDF from an HTML string using C#
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("tensorflow.pdf");
        }
    }
}
Imports IronPdf
Imports Tensorflow.Binding

Namespace IronPdfDemos
	Public Class Program
		Public Shared Sub Main()
			' Instantiate Cache and ChromePdfRenderer
			Dim renderer = New ChromePdfRenderer()

			' Prepare HTML
			Dim content = "<h1>Demonstrate TensorFlow with IronPDF</h1>"
			content &= $"<p></p>"
			content &= $"<h2></h2>"

			' Eager mode
			content &= $"<h2>Enable Eager Execution</h2>"
			content &= $"<p>tf.enable_eager_execution();</p>"

			' tf is a static TensorFlow instance
			tf.enable_eager_execution() ' Enable eager mode

			content &= $"<h2>Define tensor constants.</h2>"
			' Introduce tensor constants
			Dim a = tf.constant(5)
			Dim b = tf.constant(6)
			Dim c = tf.constant(7)

			content &= $"<p></p>"
			content &= $"<p></p>"
			content &= $"<p></p>"

			content &= $"<h2>Various tensor operations.</h2>"
			' Various tensor operations usage
			' Note: Tensors also support operators (+, *, ...)
			Dim add = tf.add(a, b)
			Dim [sub] = tf.subtract(a, b)
			Dim mul = tf.multiply(a, b)
			Dim div = tf.divide(a, b)

			content &= $"<p>var add = tf.add(a, b);</p>"
			content &= $"<p>var sub = tf.subtract(a, b);</p>"
			content &= $"<p>var mul = tf.multiply(a, b);</p>"
			content &= $"<p>var div = tf.divide(a, b);</p>"

			content &= $"<h2>Access tensors value.</h2>"
			' Tensors value
			print($"{CInt(a)} + {CInt(b)} = {CInt(add)}")
			print($"{CInt(a)} - {CInt(b)} = {CInt([sub])}")
			print($"{CInt(a)} * {CInt(b)} = {CInt(mul)}")
			print($"{CInt(a)} / {CInt(b)} = {CDbl(div)}")

			content &= $"<p>{CInt(a)} + {CInt(b)} = {CInt(add)}</p>"
			content &= $"<p>{CInt(a)} - {CInt(b)} = {CInt([sub])}</p>"
			content &= $"<p>{CInt(a)} * {CInt(b)} = {CInt(mul)}</p>"
			content &= $"<p>{CInt(a)} / {CInt(b)} = {CDbl(div)}</p>"

			' Some more operations
			Dim mean = tf.reduce_mean(tf.constant( { a, b, c }))
			Dim sum = tf.reduce_sum(tf.constant( { a, b, c }))

			content &= $"<h2>Access tensors value.</h2>"
			' Access tensors value
			print("mean =", mean.numpy())
			print("sum =", sum.numpy())

			content &= $"<p>mean = {mean.numpy()}</p>"
			content &= $"<p>sum = {sum.numpy()}</p>"

			content &= $"<h2>Matrix multiplications.</h2>"
			' Matrix multiplications with a single row
			Dim matrix1 = tf.constant(New Single(, ) {
				{ 1, 2 },
				{ 3, 4 }
			})
			Dim matrix2 = tf.constant(New Single(, ) {
				{ 5, 6 },
				{ 7, 8 }
			})
			Dim product = tf.matmul(matrix1, matrix2)

			content &= "<p>matrix1 = tf.constant(new float[,] { { { 1, 2 }}, { { 3, 4 }} })</p>"
			content &= "<p>matrix2 = tf.constant(new float[,] { { { 5, 6 }}, { { 7, 8 }} })</p>"
			content &= "<p>product = tf.matmul(matrix1, matrix2)</p>"

			content &= $"<h2>Convert Tensor to Numpy.</h2>"
			' Convert Tensor to Numpy
			print("product =", product.numpy())

			content &= $"<p>product = {product.numpy()}</p>"

			' Create a PDF from an HTML string using C#
			Dim pdf = renderer.RenderHtmlAsPdf(content)
			' Export to a file or Stream
			pdf.SaveAs("tensorflow.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

程式碼說明

讓我們分解這段代碼:

  1. 導入語句

    代碼首先通過導入必要的庫開始。 具體來說:

    using IronPdf; // This imports the IronPDF package, which is used for working with PDF files.
    using static Tensorflow.Binding; // This imports the TensorFlow library, specifically the .NET standard binding.
    using IronPdf; // This imports the IronPDF package, which is used for working with PDF files.
    using static Tensorflow.Binding; // This imports the TensorFlow library, specifically the .NET standard binding.
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel
  1. 立即執行

    這行tf.enable_eager_execution();啟用 TensorFlow 的 eager execution 模式。 在即時執行中,運算會立即被評估,這使得除錯和與張量交互更加容易。

  2. 定義張量常數

    該代碼定義了三個張量常數:abc。 這些分別被初始化為 5、6 和 7。

  3. 各種張量操作

    以下張量運算將執行:

    var add = tf.add(a, b); // Adds a and b.
    var sub = tf.subtract(a, b); // Subtracts b from a.
    var mul = tf.multiply(a, b); // Multiplies a and b.
    var div = tf.divide(a, b); // Divides a by b.
    var add = tf.add(a, b); // Adds a and b.
    var sub = tf.subtract(a, b); // Subtracts b from a.
    var mul = tf.multiply(a, b); // Multiplies a and b.
    var div = tf.divide(a, b); // Divides a by b.
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel
  1. 訪問張量值

    張量運算的結果使用print函式來列印:

    print($"{(int)a} + {(int)b} = {(int)add}");
    print($"{(int)a} - {(int)b} = {(int)sub}");
    print($"{(int)a} * {(int)b} = {(int)mul}");
    print($"{(int)a} / {(int)b} = {(double)div}");
    print($"{(int)a} + {(int)b} = {(int)add}");
    print($"{(int)a} - {(int)b} = {(int)sub}");
    print($"{(int)a} * {(int)b} = {(int)mul}");
    print($"{(int)a} / {(int)b} = {(double)div}");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

範例輸出:

- 5 + 6 = 11

- 5 - 6 = -1

- 5 * 6 = 30

- 5 / 6 = 0.8333333333333334
  1. 附加操作

    此代碼計算常數[a, b, c]的平均值和總和。

  2. PDF生成

    ChromePdfRendererRenderHtmlAsPdf 來自 IronPDF,用於將 HTML 字串渲染成 PDF 文件。

輸出

TensorFlow .NET(開發人員工作原理):圖 7 - PDF 輸出

IronPDF 授權

IronPDF 需要授權才能運行。 更多關於授權資訊可在IronPDF 授權頁面找到。 將密鑰放置在 appSettings.json 檔案中,如下所示。

{
  "IronPdf.License.LicenseKey": "The Key Here"
}

結論

總而言之,TensorFlow.NET讓 C# 開發人員能夠以 .NET 生態系統的多功能性和生產力探索機器學習和人工智慧的世界。 無論您是在構建智慧應用程式、預測分析工具或自動化決策系統,TensorFlow.NET 提供了一個強大且靈活的框架,讓C#中的機器學習潛力得以釋放。 搭配來自Iron SoftwareIronPDF庫,開發人員可以獲得開發現代應用程序的高級技能。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
Stripe .NET(開發人員如何運作)
下一個 >
Humanizer C#(開發人員如何使用)