Python TensorFlow Tutorial With Examples

TensorFlow was developed for Google’s internal use by Google Brain team, but the system is general enough to be applied to a wide variety of domains. On November 9, 2015, they decided to open source it, and release it under Apache 2.0 open source license. Today we will look into TensorFlow basics and then some Python TensorFlow example programs.

TensorFlow

TensorFlow is a library for dataflow programming. It’s a symbolic math library and is also used for application of machine learning such as neural network.

TensorFlow uses various optimization techniques to make the calculations more efficient. When it comes to computation across several machines and involves huge data sets, TensorFlow offers high scalability. These features put together make TensorFlow a perfect framework for machine learning.

TensorFlow Terminologies

In this post, we will learn more about TensorFlow and work out some examples to see how TensorFlow can be used to visualize, tweak and debug the libraries created with it, but before we get working with TensorFlow we must know what are Tensors and Tensor Processing Units.

Tensors

A tensor is central unit of data in TensorFlow. It consists of primitive values stored in shape of a multidimensional array. The number of dimensions a tensor has is called its rank.

A rank 0 tensor is just a scalar. To keep things simple, we can say that a tensor is rather a fancy name of an array and now we call dimension number as rank. Let’s have a look at what tensors look like:

A rank 1 tensor:

A rank 2 tensor:

Tensor Processing Units (TPUs)

TPU is a programmable AI accelerator designed to provide high throughput of low-precision arithmetic. It is aimed towards utilizing or running models rather than training them. As announced by Google, they have been running TPUs inside their data centres for more than a year and have found them to deliver an order of magnitude better-optimized performance per watt for machine learning.

The second-generation TPUs deliver up to 180 teraflops of performance, and when organized into clusters of 64 TPUs, provide up to 11.5 petaflops.

Getting Started with TensorFlow

We will start by installing Tensorflow.

Installing TensorFlow

We’ll use TensorFlow Python API, it works with Python 2.7 and Python 3.3 and later.

For Linux only: The GPU version requires CUDA 7.0.+ and cuDNN c2+.

Once you have these requirements fulfilled you can begin with installation. For installation we can use either conda or pip, whichever you feel more comfortable with.

The pip installation is standard to install, using pip just run the following command in your terminal (sudo is optional):

Or you can install using conda, using following command:

We are installing biopython in first command to make things easier, as it contains some more packages that we might need.

Using TensorFlow

To use TensorFlow anywhere in your script just import it using following import statement.

TensorFlow Simple Expressions

Let’s have a look into simple elements, and how they look like in TensorFlow, before we actually get to work with its elements.

TensorFlow Constants

If you need constants in your training model then you can use constant object. In TensorFlow constants are created using function constant .

The signature of the function is:

Here, shape and name are optional parameters. Let’s try to create an object using the signature:

TensorFlow Variables

TensorFlow Variables are an important part of any framework as it is impossible to program without variables, they are used to hold and update values.

In TensorFlow variables are of great use when we are training models. As constants, we have to call a constructor to initialize a variable, the initial value can be passed in as an argument. Creating a variable is easy and can be done as following:

If we want a variable to be used for calculations only and it should not be trained we can use trainable flag like this:

Variables can easily be added to a computational graph by calling a constructor.

TensorFlow Sessions

A session encapsulates the control and state of the TensorFlow runtime. The session class accepts a graph parameter. If we don’t pass any parameters to a session, it will use the default graph created in the current session.

Let’s have a look at a session in action to know it better:

Let’s start the session by running above code in terminal:

tensorflow-graph

The code prints 3.0 which should be the value of y after the computations. Also, please ignore the warning before the output. You might get that as well due to multiple Python versions and other factors.

Defining Computational Graphs

The computation graph is a built-in process in TensorFlow, we need not create an instance of Graph objects explicitly.

In TensorFlow a Graph object can be created with a simple line of code such as:

This creates an operation node to sum two numbers.

TensorFlow Placeholder

If we want to inject data into a computation graph we have to use a mechanism named as a placeholder. Placeholders are bound inside some expressions. A typical placeholder looks like:

Placeholders allow us to not to provide the data in advance for operations and computation graphs, and the data can be added in runtime from external sources.

Let’s look at an example. We’ll try to multiply two integers in TensorFlow way, we’ll be using placeholders here:

Let’s run the program and see what we get:

tensorflow-graph

Mathematics with TensorFlow

We have already had a brief about tensors, here we’ll see how can we convert a numpy array into a tensor. For the conversion we have to use a built in function convert_to_tensor. This function takes Tensor objects, Numpy arrays, Python lists and Python scalars. Let’s try to convert a 2-d array to tensor.

Let’s run the code:

tensorflow linear regression

We have tried some matrix operations above with TensorFlow, but how about element-wise operations such as sine, cosine. Well the process remains the same, however if we try a cosine operation on a vector the results so formed would be element-wise. Let’s see this in action with help of an example:

Now, let’s run this:

tensorflow linear regression

Machine Learning with TensorFlow

We’ll be looking at a minimal example of Machine Learning and how we can work an algorithm like Linear Regression with TensorFlow.

Linear Regression

Linear regression is a widely used algorithm in the field of machine learning. This algorithm is based on two important concepts of machine learning: Cost Function and Gradient Descent.

So, let’s work this algorithm with TensorFlow:

Let’s run the program. The output parameters of W and b should be same as those defined in the generate_test_values function:

tensorflow linear regression

Python TensorFlow Tutorial Conclusion

In this tutorial we have seen that TensorFlow is a powerful framework and makes it easy to work with several mathematical functions and multidimensional arrays, it also makes it easy to execute the data graphs and scaling.

TensorFlow has grown popular among developers over time. You may need some time to get used to TensorFlow, but once you do so, machine learning on a production scale is less tedious.

By admin

Leave a Reply