AYUDA .NET

TensorFlow .NET (Cómo funciona para desarrolladores)

Actualizado julio 1, 2024
Compartir:
Machine learning (ML) has revolutionized various industries, from healthcare to finance, by enabling intelligent decision-making and automation. TensorFlow, Google's open-source ML and deep learning framework, has been at the forefront of this revolution. With `TensorFlow.NET`, .NET developers can harness the power of TensorFlow within the C# ecosystem. In this article, we'll explore `TensorFlow.NET`, its features, benefits, and practical applications in C# development. Also, we will learn about a PDF generation library called `IronPDF` from `Iron Software` with a practical example.

## Understanding TensorFlow.NET

`TensorFlow.NET` is a .NET binding for TensorFlow, allowing developers to use TensorFlow functionality directly within C# and .NET application layers. Developed by the community and maintained by the SciSharp organization, `TensorFlow.NET` provides a seamless integration of TensorFlow's machine learning and neural networks' capabilities with the versatility of the .NET platform. It enables C# developers to build neural networks, train models, or training images, and deploy ML models using TensorFlow's extensive system APIs and tools.

## Key Features of TensorFlow.NET

1. **TensorFlow Compatibility**: `TensorFlow.NET` provides full compatibility with TensorFlow's APIs and operations, including tensor manipulation or activation, neural network layers, loss functions, optimizers, and utilities for data preprocessing and evaluation.
2. **High Performance**: `TensorFlow.NET` leverages TensorFlow's efficient computational graph execution engine and optimized kernels to deliver high-performance machine learning inference and training on CPUs and GPUs.
3. **Easy Integration**: `TensorFlow.NET` seamlessly integrates with existing .NET applications and libraries, enabling developers to leverage TensorFlow's capabilities without leaving the familiar C# development environment.
4. **Model Portability**: `TensorFlow.NET` allows developers to import pre-trained TensorFlow models and export trained models for inference in other TensorFlow-based environments, such as Python or mobile devices.
5. **Flexibility and Extensibility**: `TensorFlow.NET` provides flexibility for customizing and extending machine learning models using C# language features, such as LINQ (Language Integrated Query) for data manipulation and functional programming paradigms for model composition.
6. **Community Support and Documentation**: `TensorFlow.NET` benefits from an active community of contributors who provide documentation, tutorials, and examples to help developers get started with machine learning in the C# world using TensorFlow.

## Practical Examples with TensorFlow.NET

Let's explore some practical scenarios where `TensorFlow.NET` can be used to build and deploy machine learning models in C#:

1. **Loading and Using Pre-trained Models**:

```cs
    // 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. Formación de modelos personalizados:
    // 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. Evaluación y despliegue:
    // 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#

Puede encontrar más ejemplos de TensorFlow en la página de ejemplos.

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

Ejemplo de salida de Hello TensorFlow

TensorFlow .NET (Cómo funciona para desarrolladores): Figura 1 - Salida de la aplicación de consola

Ventajas del uso de TensorFlow.NET

  1. Integración sin fisuras: TensorFlow.NET lleva la potencia de TensorFlow al ecosistema .NET, permitiendo a los desarrolladores de C# aprovechar las técnicas y algoritmos de aprendizaje automático más avanzados en sus aplicaciones.

  2. Rendimiento y escalabilidad: TensorFlow.NET aprovecha el motor de ejecución optimizado de TensorFlow para ofrecer cálculos de aprendizaje automático de alto rendimiento, lo que lo hace adecuado para manejar conjuntos de datos a gran escala, imágenes de prueba y modelos complejos o densos.

  3. Entorno de desarrollo familiar: la API TensorFlow.NET permite a los desarrolladores construir e implantar modelos de aprendizaje automático utilizando características y herramientas de desarrollo del lenguaje C# que les resultan familiares, lo que reduce la curva de aprendizaje para adoptar el aprendizaje automático en aplicaciones C#.

  4. Interoperabilidad y portabilidad: TensorFlow.NET facilita la interoperabilidad con otros entornos basados en TensorFlow, permitiendo una integración perfecta de modelos de aprendizaje automático basados en C# con Python, TensorFlow Serving y TensorFlow Lite.

  5. Desarrollo impulsado por la comunidad: TensorFlow.NET se beneficia de una comunidad activa de colaboradores y usuarios que proporcionan apoyo, comentarios y contribuciones al proyecto, asegurando su continuo crecimiento y mejora.

Licencia de TensorFlow.NET

Se trata de un paquete de código abierto con licencia Apache que puede utilizarse libremente. Más información sobre la licencia en la página de la licencia.

Presentación de IronPDF

TensorFlow .NET (Cómo funciona para desarrolladores): Figura 2 - IronPDF

ironPDF es una potente biblioteca PDF en C# que permite a los desarrolladores crear, editar y firmar archivos PDF directamente a partir de entradas HTML, CSS, imágenes y JavaScript. Es una solución comercial de alto rendimiento y bajo consumo de memoria. Estas son algunas de sus principales características:

  1. Conversión de HTML a PDF: IronPDF puede convertir archivos HTML, cadenas HTML y URLs a PDFs. Por ejemplo, puedes renderizar una página web como PDF utilizando el renderizador de PDF de Chrome.

  2. Soporte multiplataforma: IronPDF funciona en varias plataformas .NET, incluidas .NET Core, .NET Standard y .NET Framework. Es compatible con Windows, Linux y macOS.

  3. Edición y firma: Puede establecer propiedades, añadir seguridad (contraseñas y permisos)e incluso aplicar firmas digitales a tus PDF.

  4. Plantillas de página y configuración: Personaliza tus PDF añadiendo encabezados, pies de página y números de página, y ajustando los márgenes. ironPDF también admite diseños adaptables y tamaños de papel personalizados.

  5. Cumplimiento de estándares: ironPDF cumple estándares PDF como PDF/A y PDF/UA. Admite la codificación de caracteres UTF-8 y gestiona activos como imágenes, CSS y fuentes.

Generar documentos PDF usando TensorFlow.NET y IronPDF

En primer lugar, cree un proyecto de Visual Studio y seleccione la siguiente plantilla de aplicación de consola.

TensorFlow .NET (Cómo funciona para desarrolladores): Figura 3 - Proyecto Visual Studio

Indique el nombre y la ubicación del proyecto.

TensorFlow .NET (Cómo funciona para desarrolladores): Figura 4 - Configuración del Proyecto

Seleccione la versión .NET necesaria en el siguiente paso y haga clic en el botón Crear.

Instale IronPDF desde el paquete NuGet del gestor de paquetes de Visual Studio.

TensorFlow .NET (Cómo funciona para los desarrolladores): Figura 5 - TensorFlow.NET

Instala los paquetes TensorFlow.NET y TensorFlow.Keras, un paquete independiente utilizado para ejecutar modelos.

TensorFlow .NET (Cómo funciona para desarrolladores): Figura 6 - Instalar paquete 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#

Código Explicación

Desglosemos el fragmento de código:

  1. Declaraciones de importación:

     El código comienza importando las bibliotecas necesarias. Específicamente:
    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. Ejecución ansiosa:

     La línea `tf.enable_eager_execution()activa el modo de ejecución eager de TensorFlow. En la ejecución ansiosa, las operaciones se evalúan inmediatamente, lo que facilita la depuración y la interacción con los tensores.
  2. Definir Constantes de Tensor:

     El código define tres constantes tensoriales: `a`, `b` y `c`. Se inicializan con los valores 5, 6 y 7, respectivamente.
  3. Varias operaciones tensoriales:

     Se realizan las siguientes operaciones tensoriales:
    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. Acceder a los valores del tensor:

     Los resultados de las operaciones tensoriales se imprimen utilizando la función `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#

Ejemplo de salida:

    - 5 + 6 = 11

    - 5 - 6 = -1

    - 5 * 6 = 30

    - 5 / 6 = 0.8333333333333334
  1. Operaciones adicionales:

     El código calcula la media y la suma de las constantes `[a, b, c]`.
  2. Generación de PDF:

     `ChromePdfRenderer` y `RenderHtmlAsPdf` de `IronPDF` se utilizan para convertir la cadena HTML en un documento PDF.

Salida

TensorFlow .NET (Cómo funciona para desarrolladores): Figura 7 - Salida PDF

Licencia IronPDF

ironPDFnecesita una licencia para funcionar. Encontrará más información sobre licencias en la página de licencias. Coloque la clave en el archivoappSettings.json` como se muestra a continuación.

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

Conclusión

En conclusión, TensorFlow.NET permite a los desarrolladores de C# explorar el mundo del aprendizaje automático y la inteligencia artificial con la versatilidad y productividad del ecosistema .NET. Tanto si está creando aplicaciones inteligentes, herramientas de análisis predictivo o sistemas automatizados de toma de decisiones, TensorFlow.NET proporciona un marco potente y flexible para liberar el potencial del aprendizaje automático en C#. Junto con la biblioteca IronPDF de Iron Software para leer y generar documentos PDF, los desarrolladores pueden adquirir conocimientos avanzados para desarrollar aplicaciones modernas.

< ANTERIOR
Stripe .NET (Cómo funciona para desarrolladores)
SIGUIENTE >
Humanizer C# (Cómo funciona para desarrolladores)

¿Listo para empezar? Versión: 2024.9 acaba de salir

Descarga gratuita de NuGet Descargas totales: 10,516,730 View Licenses >