How to Check Your TensorFlow Version in Colab?

To check your TensorFlow version in your Jupyter Notebook such as Google’s Colab, use the following two commands:

  • import tensorflow as tf This imports the TensorFlow library and stores it in the variable named tf.
  • print(tf.__version__) This prints the installed TensorFlow version number in the format x.y.z.

The following code example uses the dunder attribute __version__ on the tf module. Libraries commonly maintain their version information in this dunder attribute.

import tensorflow as tf
print(tf.__version__)

You can check this out in the following online Jupyter Notebook I’ve prepared for you using a shareable Google Colab notebook:

The interactive Jupyter Notebook opens in a new tab if you click on the image!

How to Switch the TensorFlow version on Colab?

Colab has two TensorFlow versions pre-installed:

  • 2.x version, and for legacy reasons,
  • 1.x version.

Per default, Colab uses TensorFlow version 2.x but you can switch to another version by using a bit of “TensorFlow magic” as a percentage-prefixed tensorflow_version expression in any of your cells:

%tensorflow_version 1.x

After evaluating this statement, the Colab notebook will switch to a state where the TensorFlow version 1.x is used rather than 2.x as per default.

Here’s how this will look like in a cell:

%tensorflow_version 1.x
import tensorflow as tf
print(tf.__version__)

And the output in my Colab Notebook is:

TensorFlow 1.x selected.
1.15.2

Note that if you’ve already run any cell that imports the TensorFlow library, you need to restart the notebook by choosing Runtime > Restart runtime in your Colab notebook:

As an alternative to check the TensorFlow version, you can also use the tf.version.VERSION attribute like so:

import tensorflow as tf
print(tf.version.VERSION)

This doesn’t work for some older versions of TensorFlow but the alternative tf.__version__ should work for all!