.NET 帮助

TensorFlow .NET(它是如何为开发人员工作的)

发布 2024年七月1日
分享:

机器学习 (ML) 已经通过实现智能决策和自动化革新了包括医疗到金融在内的各个行业。谷歌的开源机器学习和深度学习框架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和工具部署ML模型。

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 "为.NET生态系统带来了TensorFlow的强大功能,使C#开发人员能够在其应用程序中利用最先进的机器学习技术和算法。

  2. 性能和可扩展性:TensorFlow.NET "利用TensorFlow的优化执行引擎提供高性能的机器学习计算,使其适用于处理大规模数据集、测试图像以及复杂或密集的模型。

  3. 熟悉的开发环境:TensorFlow.NET应用程序接口允许开发人员使用熟悉的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. 编辑和签名:您可以设置属性、添加安全性 (密码和权限)甚至可以对 PDF 应用数字签名。

  4. 页面模板和设置:通过添加页眉、页脚和页码以及调整页边距自定义您的 PDF。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 软件包管理器的 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
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. 急于执行

    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 生成

    IronPDF中的ChromePdfRendererRenderHtmlAsPdf` 用于将 HTML 字符串渲染为 PDF 文档。

输出

TensorFlow .NET(如何为开发人员工作):图 7 - PDF 输出

IronPDF 许可证

IronPDF 需要许可证才能运行。有关许可证的更多信息,请参阅许可证页面。如下所示,将密钥放入 appSettings.json 文件。

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

结论

总之,"TensorFlow.NET "使 C# 开发人员能够利用 .NET 生态系统的多功能性和生产力探索机器学习和人工智能世界。无论您是要构建智能应用程序、预测分析工具还是自动决策系统,"TensorFlow.NET "都能提供一个强大而灵活的框架,让您在 C# 中释放机器学习的潜能。与 "Iron Software "提供的用于读取和生成PDF文档的 "IronPDF "库一起使用,开发人员可以获得开发现代应用程序的高级技能。

< 前一页
Stripe .NET(开发人员如何使用)
下一步 >
Humanizer C#(它是如何为开发人员工作的)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >