.NET 帮助

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

Kannaopat Udonpant
坎那帕·乌东攀
2024年七月1日
分享:

机器学习(ML)从医疗到金融,智能决策和自动化给各行各业带来了革命性的变化。 TensorFlow 是谷歌的开源 ML 和深度学习框架,一直处于这场革命的前沿。 有了 TensorFlow.NET,.NET 开发人员可以在 C# 生态系统中利用 TensorFlow 的强大功能。 在本文中,我们将探讨 TensorFlow.NET、其功能、优点以及在 C# 开发中的实际应用。 此外,我们还将通过一个实际例子了解来自 Iron Software 的名为 IronPDF 的 PDF 生成库。

了解 TensorFlow.NET

TensorFlow.NET "是 TensorFlow 的 .NET 绑定,允许开发人员直接在 C# 和 .NET 应用程序层中使用 TensorFlow 功能。 TensorFlow.NET "由社区开发并由 SciSharp 组织维护,它将 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 "受益于一个活跃的贡献者社区,该社区提供文档、教程和示例,帮助开发人员在 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);
  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);
  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");

有关 TensorFlow 的更多示例,请访问TensorFlow.NET 示例page.

// 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);
        }
    }
}

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 授权许可page.

介绍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 文件中添加数字签名,甚至将数字签名应用到 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");
        }
    }
}

代码解释

让我们来分析一下代码片段:

  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.
  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.
  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}");

输出示例:

- 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 需要许可证才能运行。 有关许可的更多信息,请访问IronPDF 许可page. 如下所示,将密钥放在 appSettings.json 文件中。

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

结论

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

Kannaopat Udonpant
坎那帕·乌东攀
软件工程师
在成为软件工程师之前,Kannapat 从日本北海道大学完成了环境资源博士学位。在攻读学位期间,Kannapat 还成为了生物生产工程系车辆机器人实验室的成员。2022年,他利用自己的 C# 技能加入了 Iron Software 的工程团队,专注于 IronPDF。Kannapat 珍视他的工作,因为他能直接向编写 IronPDF 大部分代码的开发者学习。除了同伴学习,Kannapat 还享受在 Iron Software 工作的社交方面。不写代码或文档时,Kannapat 通常在 PS5 上玩游戏或重看《最后生还者》。
< 前一页
Stripe .NET(开发人员如何使用)
下一步 >
Humanizer C#(它是如何为开发人员工作的)