Skip to footer content
.NET HELP

TensorFlow .NET (How It Works For Developers)

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, 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, 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:

    // 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
  2. Training Custom Models:

    // Create a neural network model using TensorFlow.NET APIs
    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
    model.Fit(x_train, y_train, epochs: 10, batchSize: 32);
    // Create a neural network model using TensorFlow.NET APIs
    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
    model.Fit(x_train, y_train, epochs: 10, batchSize: 32);
    ' Create a neural network model using TensorFlow.NET APIs
    Dim input As New Input(Shape.Scalar)
    Dim output = (New Dense(1, Activation.ReLU)).Forward(input)
    ' Compile the model with loss function and optimizer algorithms
    Dim model As New Model(input, output)
    model.Compile(optimizer:= New SGD(), loss:= Losses.MeanSquaredError)
    ' Train the model with training data
    model.Fit(x_train, y_train, epochs:= 10, batchSize:= 32)
    $vbLabelText   $csharpLabel
  3. Evaluation and Deployment:

    // 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");
    ' Evaluate the trained model on test data
    Dim evaluation = model.Evaluate(x_test, y_test)
    ' Export the trained model for deployment
    model.SaveModel("trained_model.pb")
    $vbLabelText   $csharpLabel

More examples of TensorFlow can be found on the TensorFlow.NET Examples page.

// Use static TensorFlow
using static Tensorflow.Binding;

namespace IronPdfDemos
{
    public class TensorFlow
    {
        public static void Execute()
        {
            // Create a TensorFlow constant
            var hello = tf.constant("Hello, TensorFlow!");
            Console.WriteLine(hello);
        }
    }
}
// Use static TensorFlow
using static Tensorflow.Binding;

namespace IronPdfDemos
{
    public class TensorFlow
    {
        public static void Execute()
        {
            // Create a TensorFlow constant
            var hello = tf.constant("Hello, TensorFlow!");
            Console.WriteLine(hello);
        }
    }
}
' Use static TensorFlow
Imports Tensorflow.Binding

Namespace IronPdfDemos
	Public Class TensorFlow
		Public Shared Sub Execute()
			' Create a TensorFlow constant
			Dim hello = tf.constant("Hello, TensorFlow!")
			Console.WriteLine(hello)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Sample Hello TensorFlow Output

TensorFlow .NET (How It Works For Developers): Figure 1 - Console App Output

Benefits of Using TensorFlow.NET

  1. Seamless Integration: TensorFlow.NET brings the power of TensorFlow to the .NET ecosystem, enabling C# developers to leverage state-of-the-art machine learning techniques and algorithms in their applications.
  2. Performance and Scalability: TensorFlow.NET leverages TensorFlow's optimized execution engine to deliver high-performance machine learning computations, making it suitable for handling large-scale datasets and complex models.
  3. Familiar Development Environment: TensorFlow.NET API allows developers to build and deploy machine learning models using familiar C# language features and development tools, reducing the learning curve for adopting machine learning in C# applications.
  4. Interoperability and Portability: TensorFlow.NET facilitates interoperability with other TensorFlow-based environments, enabling seamless integration of C#-based machine learning models with Python, TensorFlow Serving, and TensorFlow Lite.
  5. Community-driven Development: TensorFlow.NET benefits from an active community of contributors and users who provide support, feedback, and contributions to the project, ensuring its continued growth and improvement.

TensorFlow.NET License

It is an open-source Apache Licensed package that can be freely used. More about the license can be read on the TensorFlow.NET License page.

Introducing IronPDF

TensorFlow .NET (How It Works For Developers): Figure 2 - IronPDF

IronPDF is a powerful C# PDF library that allows developers to create, edit, and sign PDFs directly from HTML, CSS, images, and JavaScript inputs. It’s a commercial-grade solution with high performance and a low memory footprint. Here are some key features:

  1. HTML to PDF Conversion: IronPDF can convert HTML files, HTML strings, and URLs to PDFs. For example, you can render a webpage as a PDF using the Chrome PDF renderer.
  2. Cross-Platform Support: IronPDF works on various .NET platforms, including .NET Core, .NET Standard, and .NET Framework. It’s compatible with Windows, Linux, and macOS.
  3. Editing and Signing: You can set properties, add security (passwords and permissions), and even apply digital signatures to your PDFs.
  4. Page Templates and Settings: Customize your PDFs by adding headers, footers, and page numbers, and adjusting margins. IronPDF also supports responsive layouts and custom paper sizes.
  5. Standards Compliance: IronPDF adheres to PDF standards such as PDF/A and PDF/UA. It supports UTF-8 character encoding and handles assets like images, CSS, and fonts.

Generate PDF Documents Using TensorFlow.NET and IronPDF

First, create a Visual Studio project and select the Console App template below.

TensorFlow .NET (How It Works For Developers): Figure 3 - Visual Studio Project

Provide project name and location.

TensorFlow .NET (How It Works For Developers): Figure 4 - Project Configuration

Select the required .NET version in the next step and click the Create button.

Install IronPDF from NuGet Package from the Visual Studio Package Manager.

TensorFlow .NET (How It Works For Developers): Figure 5 - TensorFlow.NET

Install packages TensorFlow.NET and TensorFlow.Keras, an independent package used to run models.

TensorFlow .NET (How It Works For Developers): Figure 6 - Install package 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 content for the PDF
            var content = "<h1>Demonstrate TensorFlow with IronPDF</h1>";
            content += "<h2>Enable Eager Execution</h2>";
            content += "<p>tf.enable_eager_execution();</p>";

            // Enable eager execution mode in TensorFlow
            tf.enable_eager_execution();

            // Define tensor constants
            content += "<h2>Define Tensor Constants</h2>";
            var a = tf.constant(5);
            var b = tf.constant(6);
            var c = tf.constant(7);

            // Perform various tensor operations
            content += "<h2>Various Tensor Operations</h2>";
            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>";

            // Output tensor values to HTML content
            content += "<h2>Access Tensor Values</h2>";
            content += $"<p>{a.numpy()} + {b.numpy()} = {add.numpy()}</p>";
            content += $"<p>{a.numpy()} - {b.numpy()} = {sub.numpy()}</p>";
            content += $"<p>{a.numpy()} * {b.numpy()} = {mul.numpy()}</p>";
            content += $"<p>{a.numpy()} / {b.numpy()} = {div.numpy()}</p>";

            // Perform additional 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>Additional Operations</h2>";
            content += $"<p>mean = {mean.numpy()}</p>";
            content += $"<p>sum = {sum.numpy()}</p>";

            // Perform matrix multiplication
            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 += "<h2>Matrix Multiplications</h2>";
            content += "<p>Multiplication Result:</p>";
            content += $"<p>product = {product.numpy()}</p>";

            // Render HTML content to PDF
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Save PDF to file
            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 content for the PDF
            var content = "<h1>Demonstrate TensorFlow with IronPDF</h1>";
            content += "<h2>Enable Eager Execution</h2>";
            content += "<p>tf.enable_eager_execution();</p>";

            // Enable eager execution mode in TensorFlow
            tf.enable_eager_execution();

            // Define tensor constants
            content += "<h2>Define Tensor Constants</h2>";
            var a = tf.constant(5);
            var b = tf.constant(6);
            var c = tf.constant(7);

            // Perform various tensor operations
            content += "<h2>Various Tensor Operations</h2>";
            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>";

            // Output tensor values to HTML content
            content += "<h2>Access Tensor Values</h2>";
            content += $"<p>{a.numpy()} + {b.numpy()} = {add.numpy()}</p>";
            content += $"<p>{a.numpy()} - {b.numpy()} = {sub.numpy()}</p>";
            content += $"<p>{a.numpy()} * {b.numpy()} = {mul.numpy()}</p>";
            content += $"<p>{a.numpy()} / {b.numpy()} = {div.numpy()}</p>";

            // Perform additional 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>Additional Operations</h2>";
            content += $"<p>mean = {mean.numpy()}</p>";
            content += $"<p>sum = {sum.numpy()}</p>";

            // Perform matrix multiplication
            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 += "<h2>Matrix Multiplications</h2>";
            content += "<p>Multiplication Result:</p>";
            content += $"<p>product = {product.numpy()}</p>";

            // Render HTML content to PDF
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Save PDF to file
            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 content for the PDF
			Dim content = "<h1>Demonstrate TensorFlow with IronPDF</h1>"
			content &= "<h2>Enable Eager Execution</h2>"
			content &= "<p>tf.enable_eager_execution();</p>"

			' Enable eager execution mode in TensorFlow
			tf.enable_eager_execution()

			' Define tensor constants
			content &= "<h2>Define Tensor Constants</h2>"
			Dim a = tf.constant(5)
			Dim b = tf.constant(6)
			Dim c = tf.constant(7)

			' Perform various tensor operations
			content &= "<h2>Various Tensor Operations</h2>"
			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>"

			' Output tensor values to HTML content
			content &= "<h2>Access Tensor Values</h2>"
			content &= $"<p>{a.numpy()} + {b.numpy()} = {add.numpy()}</p>"
			content &= $"<p>{a.numpy()} - {b.numpy()} = {[sub].numpy()}</p>"
			content &= $"<p>{a.numpy()} * {b.numpy()} = {mul.numpy()}</p>"
			content &= $"<p>{a.numpy()} / {b.numpy()} = {div.numpy()}</p>"

			' Perform additional operations
			Dim mean = tf.reduce_mean(tf.constant( { a, b, c }))
			Dim sum = tf.reduce_sum(tf.constant( { a, b, c }))

			content &= "<h2>Additional Operations</h2>"
			content &= $"<p>mean = {mean.numpy()}</p>"
			content &= $"<p>sum = {sum.numpy()}</p>"

			' Perform matrix multiplication
			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 &= "<h2>Matrix Multiplications</h2>"
			content &= "<p>Multiplication Result:</p>"
			content &= $"<p>product = {product.numpy()}</p>"

			' Render HTML content to PDF
			Dim pdf = renderer.RenderHtmlAsPdf(content)
			' Save PDF to file
			pdf.SaveAs("tensorflow.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Code Explanation

Let’s break down the code snippet:

  1. Import Statements:

    The code begins by importing the necessary libraries. Specifically:

    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.
    Imports IronPdf ' This imports the IronPDF package, which is used for working with PDF files.
    Imports Tensorflow.Binding ' This imports the TensorFlow library, specifically the .NET standard binding.
    $vbLabelText   $csharpLabel
  2. Eager Execution:

    The line tf.enable_eager_execution(); enables TensorFlow’s eager execution mode. In eager execution, operations are evaluated immediately, making it easier to debug and interact with tensors.

  3. Define Tensor Constants:

    The code defines three tensor constants: a, b, and c. These are initialized with the values 5, 6, and 7, respectively.

  4. Various Tensor Operations:

    The following tensor operations are performed:

    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.
    Dim add = tf.add(a, b) ' Adds a and b.
    Dim [sub] = tf.subtract(a, b) ' Subtracts b from a.
    Dim mul = tf.multiply(a, b) ' Multiplies a and b.
    Dim div = tf.divide(a, b) ' Divides a by b.
    $vbLabelText   $csharpLabel
  5. Access Tensor Values:

    The results of the tensor operations are included in the HTML content:

    content += $"<p>{a.numpy()} + {b.numpy()} = {add.numpy()}</p>";
    content += $"<p>{a.numpy()} - {b.numpy()} = {sub.numpy()}</p>";
    content += $"<p>{a.numpy()} * {b.numpy()} = {mul.numpy()}</p>";
    content += $"<p>{a.numpy()} / {b.numpy()} = {div.numpy()}</p>";
    content += $"<p>{a.numpy()} + {b.numpy()} = {add.numpy()}</p>";
    content += $"<p>{a.numpy()} - {b.numpy()} = {sub.numpy()}</p>";
    content += $"<p>{a.numpy()} * {b.numpy()} = {mul.numpy()}</p>";
    content += $"<p>{a.numpy()} / {b.numpy()} = {div.numpy()}</p>";
    content += $"<p>{a.numpy()} + {b.numpy()} = {add.numpy()}</p>"
    content += $"<p>{a.numpy()} - {b.numpy()} = {[sub].numpy()}</p>"
    content += $"<p>{a.numpy()} * {b.numpy()} = {mul.numpy()}</p>"
    content += $"<p>{a.numpy()} / {b.numpy()} = {div.numpy()}</p>"
    $vbLabelText   $csharpLabel
  6. Additional Operations:

    The code calculates the mean and sum of the constants [a, b, c].

  7. Matrix Multiplications:

    It performs matrix multiplication between matrix1 and matrix2 and displays the result.

  8. PDF Generation:

    ChromePdfRenderer and RenderHtmlAsPdf from IronPDF are used to render the HTML string into a PDF document.

Output

TensorFlow .NET (How It Works For Developers): Figure 7 - PDF Output

IronPDF License

IronPDF needs a license to run. More on licensing can be found on the IronPDF Licensing page. Place the key in the appSettings.json file as shown below.

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

Conclusion

In conclusion, TensorFlow.NET empowers C# developers to explore the world of machine learning and artificial intelligence with the versatility and productivity of the .NET ecosystem. Whether you're building intelligent applications, predictive analytics tools, or automated decision-making systems, TensorFlow.NET provides a powerful and flexible framework for unleashing the potential of machine learning in C#. Together with the IronPDF library from Iron Software, developers can gain advanced skills to develop modern applications.

Frequently Asked Questions

How can I integrate machine learning into my C# application?

You can use TensorFlow.NET, a .NET binding for TensorFlow, which allows you to build, train, and deploy machine learning models within your C# application. It provides full compatibility with TensorFlow's powerful APIs.

What are the key features of TensorFlow.NET?

TensorFlow.NET offers features such as full compatibility with TensorFlow APIs, high performance through TensorFlow's computational engine, easy integration with .NET systems, model portability, and strong community support.

How can I convert HTML to PDF in a .NET application?

You can use IronPDF to convert HTML to PDF in a .NET application. IronPDF allows conversion from HTML, CSS, and JavaScript inputs into PDF documents, offering cross-platform compatibility and advanced PDF manipulation capabilities.

Can TensorFlow.NET be used to import models from Python?

Yes, TensorFlow.NET supports model portability, allowing you to import models created in environments like Python and use them within your .NET applications.

What is the potential of combining TensorFlow.NET and IronPDF?

Combining TensorFlow.NET and IronPDF allows developers to build intelligent applications that can perform complex machine learning computations and present the results in well-formatted PDF documents, enhancing documentation and reporting processes.

Is TensorFlow.NET suitable for cross-platform development?

Yes, TensorFlow.NET can be used in cross-platform .NET environments, allowing developers to build applications compatible with various operating systems.

How can I edit and sign PDFs in a C# application?

IronPDF provides functionality for editing and signing PDF documents within a C# application, allowing for robust PDF manipulation and management.

What support is available for developers using TensorFlow.NET?

TensorFlow.NET is supported by a strong community and comprehensive documentation, making it easier for developers to find resources and examples to aid in their development process.

How does TensorFlow.NET enhance the C# development environment?

TensorFlow.NET enhances the C# development environment by integrating TensorFlow's machine learning capabilities, allowing developers to leverage the full power of TensorFlow without leaving the .NET ecosystem.

Where can developers find practical examples of using IronPDF?

Developers can find practical examples of using IronPDF on the IronPDF documentation page and through various online resources and community forums dedicated to .NET PDF manipulation.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of ...Read More