.NET 帮助

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

机器学习 (ML) 已经通过实现智能决策和自动化彻底改变了包括医疗保健和金融在内的各个行业。 TensorFlow 是谷歌的开源 ML 和深度学习框架,一直处于这场革命的前沿。 使用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 和工具部署 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)
$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标准,如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
$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的即时执行模式。 在急切执行中,操作会立即得到评估,从而使调试和与张量的交互变得更加容易。

  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 Licensing页面找到。 将密钥放在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#(它是如何为开发人员工作的)