.NET HELP

TensorFlow .NET (How It Works For Developers)

Published July 1, 2024
Share:

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:

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

    // 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);
    ' Create a neural network model using TensorFlow.NET APIs and metrics
    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 just like Python
    model.Fit(x_train, y_train, epochs:= 10, batchSize:= 32)
    VB   C#
  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")
    VB   C#

More examples of TensorFlow can be found on the examples 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);
        }
    }
}
' 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#

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, test images, and complex or dense 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 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
            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#

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.
    VB   C#
  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.
    VB   C#
  5. Access Tensor Values:

    The results of the tensor operations are printed using the print function:

    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}");
    Imports System
    
    print($"{CInt(Math.Truncate(a))} + {CInt(Math.Truncate(b))} = {CInt(Math.Truncate(add))}")
    print($"{CInt(Math.Truncate(a))} - {CInt(Math.Truncate(b))} = {CInt(Math.Truncate([sub]))}")
    print($"{CInt(Math.Truncate(a))} * {CInt(Math.Truncate(b))} = {CInt(Math.Truncate(mul))}")
    print($"{CInt(Math.Truncate(a))} / {CInt(Math.Truncate(b))} = {CDbl(div)}")
    VB   C#

    Example Output:

    • 5 + 6 = 11
    • 5 - 6 = -1
    • 5 * 6 = 30
    • 5 / 6 = 0.8333333333333334
  6. Additional Operations:

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

  7. 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 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 to read and generate PDF documents, developers can gain advanced skills to develop modern applications.

< PREVIOUS
Stripe .NET (How It Works For Developers)
NEXT >
Humanizer C# (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >