No Module Named TensorFlow: The Unofficial Troubleshooting Guide

Ben Cook • Posted 2020-12-31 • Last updated 2021-03-24

If you get an ImportError or ModuleNotFoundError for TensorFlow, you almost certainly failed to install it correctly in the Python environment you’re using. That means either a) you failed to install TensorFlow or b) you installed it in the wrong environment. Don’t worry! It’s a very common mistake.

Failure to install TensorFlow is beyond the scope of this post. Early versions of the package were indeed difficult to install, but recent versions should all be installable with pip. If that doesn’t work for you, then you should probably just use Docker.

But installing it in the wrong environment is more interesting. One problem with Python is that you will often need multiple different environments on your machine. This makes it easy to install things in the wrong environment, making them inaccessible to the program you’re trying to run.

Quick hacks

If you’re in a Jupyter notebook, you can quickly install TensorFlow in the environment running the kernel with the following cell:

import sys

!$sys.executable -m pip install tensorflow

The ! runs a shell command, the $ passes Python variables into the shell command and sys.executable returns the path to the Python interpreter for the current environment.

If you just need it in the main Python on your local machine, you can run the equivalent command:

python -m pip install tensorflow

Make sure python is pointing to the interpreter you actually want to use.

Better solutions

A better solution is to use a new Anaconda environment for your project. Once you’ve installed Anaconda, you can create a new environment and install TensorFlow:

conda create --name tensorflow-env python=3.8 pip
conda activate tensorflow-env
pip install tensorflow

Note: you can use a Python version other than 3.8, but as of this post the latest TensorFlow does not yet support 3.9.

If you need a version of TensorFlow before 2.0, you will need to install an earlier version of Python:

conda create --name tensorflow-env python=3.6 pip
conda activate tensorflow-env
pip install "tensorflow<2.0"

And as with failure to install TensorFlow, another option is to use Docker. This is a pretty good solution because it keeps TensorFlow and all its dependencies together without polluting your actual machine.

Final notes

A couple final notes:

  • If you’re getting an error about Keras specifically like “no module named keras” then it’s time to join the future. The Keras API now comes with TensorFlow. Hello, tf.keras!
  • If you want to uninstall TensorFlow, check out my troubleshooting guide!