Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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.
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.
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.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.TensorFlow.NET
seamlessly integrates with existing .NET applications and libraries, enabling developers to leverage TensorFlow's capabilities without leaving the familiar C# development environment.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.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.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.Let's explore some practical scenarios where TensorFlow.NET
can be used to build and deploy machine learning models in C#:
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)
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)
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")
More examples of TensorFlow can be found on the TensorFlow.NET 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
Sample Hello TensorFlow Output
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.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.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.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.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.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.
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:
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.IronPDF
works on various .NET platforms, including .NET Core, .NET Standard, and .NET Framework. It’s compatible with Windows, Linux, and macOS.IronPDF
also supports responsive layouts and custom paper sizes.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.First, create a Visual Studio project and select the Console App template below.
Provide project name and location.
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.
Install packages TensorFlow.NET
and TensorFlow.Keras
, an independent package used to run models.
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
Let’s break down the code snippet:
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.
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.
Define Tensor Constants:
The code defines three tensor constants: a
, b
, and c
. These are initialized with the values 5, 6, and 7, respectively.
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.
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)}")
Example Output:
Additional Operations:
The code calculates the mean and sum of the constants [a, b, c]
.
PDF Generation:
ChromePdfRenderer
and RenderHtmlAsPdf
from IronPDF
are used to render the HTML string into a PDF document.
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"
}
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.
9 .NET API products for your office documents