.NET 幫助

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

發佈 2024年7月1日
分享:

機器學習 (機器學習) 顛覆了各行各業,從醫療到金融,通過實現智能決策和自動化。谷歌的開源機器學習和深度學習框架TensorFlow一直處於這場變革的前沿。通過 TensorFlow.NET,.NET 開發人員可以在 C# 生態系統中利用 TensorFlow 的強大功能。在本文中,我們將探討 TensorFlow.NET、其功能、優點以及在 C# 開發中的實際應用。此外,我們將了解來自 Iron Software 的 PDF 生成庫 IronPDF 以及一個實用的示例。

認識 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」受益於活躍的貢獻者社群,他們提供文件、教學和範例,幫助開發人員使用TensorFlow在C#世界中開始機器學習。

使用 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)
VB   C#
  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
VB   C#
  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
VB   C#

更多 TensorFlow 的範例可以在範例頁面找到。

// 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
VB   C#

樣本 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 許可套件,可以自由使用。關於許可證的詳情可以在許可證頁面上閱讀。

介紹 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. 編輯和簽署:您可以設置屬性,添加安全... (密碼和權限),甚至可以在您的 PDFs 上應用數位簽名。

  4. 頁面範本和設定:通過添加頁眉、頁腳和頁碼以及調整邊距來自訂您的 PDFs。IronPDF 也支持響應式佈局和自定義紙張大小。

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

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

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

TensorFlow .NET(它對開發者的工作原理):圖3 - Visual Studio專案

請提供專案名稱和位置。

TensorFlow .NET(開發人員如何運作):圖 4 - 專案配置

選擇所需的 .NET 版本,然後點擊創建按鈕。

從 Visual Studio 套件管理器中安裝 IronPDF NuGet 套件。

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
VB   C#

代碼説明

讓我們來分解一下這段代碼:

  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
VB   C#
  1. Eager Execution:

    The line tf.enable_eager_execution();`啟用TensorFlow的立即執行模式。在立即執行模式下,操作會立即評估,這使得調試和與張量進行互動變得更容易。

  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
VB   C#
  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
VB   C#

範例輸出:

- 5 + 6 = 11

- 5 - 6 = -1

- 5 * 6 = 30

- 5 / 6 = 0.8333333333333334
  1. 附加運算:

    程式碼計算常數的平均值和總和[a,b,c]`。

  2. PDF 生成:

    使用 IronPDFChromePdfRendererRenderHtmlAsPdf 將 HTML 字串渲染為 PDF 文件。

輸出

TensorFlow .NET(開發人員如何使用):圖7 - PDF輸出

IronPDF License

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

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

結論

總之,TensorFlow.NET 使 C# 開發人員能夠探索機器學習和人工智慧的世界,同時保有 .NET 生態系統的多功能性和生產力。無論您是在構建智能應用程式、預測分析工具還是自動化決策系統,TensorFlow.NET 都提供了一個強大且靈活的框架,在 C# 中釋放機器學習的潛力。結合來自 Iron SoftwareIronPDF 庫,以讀取和生成 PDF 文件,開發人員可以獲得開發現代應用程式的先進技能。

< 上一頁
Stripe .NET(開發人員如何運作)
下一個 >
Humanizer C#(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >