Step-by-step Guide to Install TensorFlow 2

Due to its ease-of-use, efficiency, and cross-compatibility TensorFlow 2.0 is going to change the landscape of Deep Learning. Here we will learn to install and set it up. We will also implement MNIST classification with TF 2.0.

Chitta Ranjan
8 min readJun 14, 2019

<<Download the free book, Understanding Deep Learning, to learn more>>

TensorFlow 2.0 is going to change the landscape of Deep Learning. It has made,

  • model building simpler,
  • production deployment on any platform more robust, and
  • enables powerful experimentation for research.

With these, Deep Learning is going to become more mainstream in various areas in research and industry.

TF 2.0 has Keras API integrated in it. Keras is an extremely popular high-level API for building and training deep learning models. Before going forward it is important to know,

  • TF 1.x also supports Keras, but in 2.0 Keras is integrated tightly with the rest of the TensorFlow platform. 2.0 is providing a single high-level API to reduce confusion and enable advanced capabilities.
  • The Keras commonly used now is an independent open source project found at www.keras.io (June, 2019). However, Keras is an API spec that is now also available in TensorFlow (see [1] for details).

I recommend reading [1] and [2] to know more details on the benefits of TensorFlow 2.0. In summary, TF 2.0 has brought the ease-of-implementation along with immense computational efficiency, and compatibility with any platform, such as, Android, iOS and embedded systems like a Raspberry Pi and Edge TPUs.

Achieving these were difficult before and required investing time on finding alternate ways. As TensorFlow 2.0 has brought all of them, it is imperative to migrate to it sooner than later.

To that end, here we will learn installing and setting up TensorFlow 2.0.

Prerequisites

Option 1: Python 3.4+ through Anaconda

Anaconda with Jupyter provides a simpler approach for installing Python and working on it.

Installing Anaconda is relatively straightforward. Follow this link with the latest Python 3.4+: https://jupyter.org/install

Similar to pip, with Anaconda we have conda for creating virtual environments and installing packages.

Option 2: Python (without Anaconda)

a. Install Python 3.4+

Check your current versions.

$ python --version

or,

$ python3 --version

I have different Python on my Mac (Python 3.6 on Anaconda) and Ubuntu (Python 3.7). The output I see on them are,

Python 3.6.8 :: Anaconda custom (x86_64)# MacPython 3.7.1# Ubuntu

Either Python within Anaconda or otherwise will work.

If your version is not 3.4+, install it as follows.

$ brew update
$ brew install python # Installs Python 3
$ sudo apt install python3-dev python3-pip

b. Install virtualenv

virtualenv is required to create a virtual environment. Its requirement is explained in the next section.

Mac OS

$ sudo pip3 install -U virtualenv# system-wide install

Ubuntu

$ sudo pip3 install -U virtualenv# system-wide install

Note: pip (instead of pip3) is also used sometimes. If unsure between the two, use pip3. You will not go wrong with pip3. If you want to know whether you could use pip , run the following

$ pip3 --version
pip 19.1.1 from /Users/inferno/anaconda/lib/python3.6/site-packages/pip (python 3.6)
$ pip --version
pip 19.1.1 from /Users/inferno/anaconda/lib/python3.6/site-packages/pip (python 3.6)

In my system, the versions are the same for both pip and pip3. Therefore, I can use either of them.

In the following, we will look at the installations steps with both.

Step 1. Create a virtual environment in Python.

Why we want a virtual environment?

A virtual environment is an isolated environment for Python projects. Inside a virtual environment we can have a completely independent set of packages (dependencies) and settings that will not conflict with anything in other virtual environment or with the default local Python environment.

This means we can keep different versions of the same package, e.g. we can use scikit-learn 0.1 for one project, and scikit-learn 0.22 for another project on the same system but in different virtual environments.

Instantiate a virtual environment

Ubuntu/Mac (Python without Anaconda)

$ virtualenv --system-site-packages -p python3 tf_2

The above command will create a virtual environment tf_2. Understanding the command,

  • virtualenv will create a virtual environment.
  • --system-site-packages allows the projects within the virtual environment tf_2 access the global site-packages. The default setting does not allow this access (--no-site-packages was used before for this default setting but now deprecated.)
  • -p python3 is used to set the Python interpreter for tf_2. This argument can be skipped if the virtualenv was installed with Python3. By default, that is the python interpreter for the virtual environment. Another option for setting Python3.x as interpreter is $ virtualenv --system-site-packages --python=python3.7 tf_2. This gives more control.
  • tf_2 is the name of the virtual environment we created. This creates a physical directory at the location of the virtual environments. This /tf_2 directory contains a copy of the Python compiler and all the packages we will install later.

Conda on Ubuntu/Mac (Python from Anaconda)

If you are using Conda, you can create the virtual environment as,

$ conda create -n tf_2

The above command will also create a virtual environment tf_2. Unlike before, we do not require to install a different package for creating a virtual environment. The in-built conda command provides this.

Understanding the command,

  • conda can be used to create virtual environments, install packages, list the installed packages in the environment, and so on. In short, conda performs operations that pip and virtualenv does. However, conda does not replace pip as some packages are available on pip but not on conda.
  • create is used to create a virtual environment.
  • -n is an argument specific to create. -n is used to name the virtual environment. The value of n, i.e. the environment name, here is tf_2.
  • Additional useful arguments: similar to--system-site-packages in virtualenv, --use-local can be used.

Step 2. Activate the virtual environment.

Activate the virtual environment.

Ubuntu/Mac (Python without Anaconda)

$ source tf_2/bin/activate

Conda on Ubuntu/Mac (Python from Anaconda)

$ conda activate tf_2

After the activation, the terminal will change to this (tf_2) $ .

Step 3. Install TensorFlow 2.0.

The following instructions are the same for the both Python options.

Before starting the TensorFlow installation, we will update pip.

(tf_2) $ pip install --upgrade pip

Now, install TensorFlow.

(tf_2) $ pip install --upgrade tensorflow==2.0.0-rc1

The tensorflow argument above installs a 2.0.0-rc1 CPU-only version.

Choose the appropriate TensorFlow version from https://www.tensorflow.org/install/pip .

At the time of writing this article, we have tensorflow 2.0.0-rc1. This is recommended. We can change the argument to one of the following based on our requirement.

  • tensorflow==2.0.0-rc1 -Preview TF 2.0 RC build for CPU-only (recommended).
  • tensorflow-gpu==2.0.0-rc1 -Preview TF 2.0 RC build with GPU support.
  • tensorflow -Latest stable release for CPU-only.
  • tensorflow-gpu -Latest stable release with GPU support.
  • tf-nightly -Preview nightly build for CPU-only.
  • tf-nightly-gpu -Preview nightly build with GPU support.

Note: we will use pip install for conda as well. TensorFlow is not available with conda.

Step 4. Test the installation.

To quickly test the installation through the terminal, use

(tf_2) $ python -c "import tensorflow as tf; x = [[2.]]; print('tensorflow version', tf.__version__); print('hello, {}'.format(tf.matmul(x, x)))"

The output will be (ignoring the system messages),

tensorflow version 2.0.0-rc1
hello, [[4.]]

Pay attention to the TensorFlow version output. If it is not the version you installed (2.0.0-rc1, in this case), then something went wrong. Most likely, there is a prior installed TensorFlow and/or the current installation failed.

TensorFlow 2.0 Example

We will test and learn the TensorFlow 2.0 with MNIST ( fashion_mnist) image classification example.

import matplotlib.pyplot as pltimport tensorflow as tf
layers = tf.keras.layers
import numpy as npprint(tf.__version__)

Make sure the tf.__version__ outputs 2.x. If the version is older, check the installation or the virtual environment.

Download the fashion_mnist data from the tf open datasets and pre-process it.

mnist = tf.keras.datasets.fashion_mnist(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

To get familiarized with the data, we will plot a few examples from it.

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(x_train[i], cmap=plt.cm.binary)
plt.xlabel(class_names[y_train[i]])
plt.show()

Now, we will build the model layer-by-layer.

model = tf.keras.Sequential()
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)

Note that this model is only for demonstration and, therefore, trained on just five epochs.

We will now test the model accuracy on the test data.

model.evaluate(x_test, y_test)

We will visualize one of the predictions. We will use some UDFs from [ 3].

def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])

plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)

if predicted_label == true_label:
color = 'blue'
else:
color = 'red'

plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)

thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')

We will find the prediction, i.e. the probability of each image belonging to each of the 10 classes, for the test images.

predictions = model.predict(x_test)i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, y_test, x_test)
plt.subplot(1,2,2)
plot_value_array(i, predictions, y_test)
plt.show()

As we can see in the plot above, the prediction probability of ‘Ankle boot’ is the highest. To further confirm, we output the predicted label as,

predicted_label = class_names[np.argmax(predictions[0])]
print('Actual label:', class_names[y_test[0]])
print('Predicted label:', predicted_label)

Step 5. Deactivate the virtual environment

Before closing, we will deactivate the virtual environment.

For virtualenv use,

(tf_2) $ deactivate

For conda use,

(tf_2) $ conda deactivate

The GitHub repository with the MNIST example on TensorFlow 2.0 is here.

Conclusion

  • TensorFlow 2.0 has brought the easy-to-use capabilities of keras API, e.g. layer-by-layer modeling.
  • We learned installing TensorFlow 2.0.
  • We went through a real MNIST data classification example with TF 2.0.

--

--