Modulenotfounderror: no module named ‘tensorflow.contrib’

In this TensorFlow tutorial, I will explain how to solve the error Modulenotfounderror: no module named ‘tensorflow.contrib’ or no module named ‘tensorflow.contrib’.

You will learn two methods to solve this error. The first method is related to the TensorFlow version, and the second is about migrating TensorFlow.

Modulenotfounderror: no module named ‘tensorflow.contrib’

The error Modulenotfounderror: no module named ‘tensorflow.contrib’ means no module tensorflow.contrib.

If you run the code below, you will get that error.

import tensorflow.contrib
Modulenotfounderror no module named 'tensorflow.contrib'

Look at the output; the error appears. The reason behind this error is the version of TensorFlow you are using.

Let me explain to you in a bit of detail. Here, you are importing the ‘contrib’ submodule from TensorFlow. Your import statement is correct, and nothing is wrong, but you are executing that code in the TensorFlow version 2.x environment.

Your code is compatible with TensorFlow version 1.x, but you have updated TensorFlow to the latest version, something 2.x, which is the reason for that error. The latest version of TensorFlow 2.x has removed the ‘session’ and ‘contrib’ sub-module from the TensorFlow library.

Import the ‘contrib’ submodule from the TensorFlow version 1.x to make that code work correctly. This is your solution.

For that, downgrade the tensorflow version to something 1.14.

First, uninstall the already installed version; if it is the latest version, reinstall it with the older version. To uninstall TensorFlow 2.x, you can easily use the command pip uninstall TensorFlow.

pip uninstall tensorflow

You can use the command below to install an older version of TensorFlow 1.x.

pip install tensorflow==1.13.2

Remember, the above code may not work because it is a very old version of TensorFlow, which may not exist in the repository.

READ:  NumPy linspace in Python [7+ Examples]

If the above does not work, you have another solution: migrate to TensorFlow 2.x. This means that if you are using code written for TensorFlow version 1, you will need to migrate it to TensorFlow version 2.x.

Also, TensorFlow has a script called ‘tf_upgrade_v2’ that can help you with the migration process, but manual intervention is required to adjust the code.

If you want to know more about migrating to TensorFlow version 2.x, visit this page: Migrate to TensorFlow 2  |  TensorFlow Core.

I hope you understand how to fix the error Modulenotfounderror: no module named ‘tensorflow.contrib’.


In this TensorFlow tutorial, you learned how to resolve the error Modulenotfounderror: no module named ‘tensorflow.contrib’.

You learned to fix that error; Tensorflow version 1.13.2 is required. You also learned that we must migrate our Tensorflow code to the latest version using the script ‘tf_upgrade_v2’.

You may like to read: