Modulenotfounderror no module named tensorflow windows 10

Solutions tried: pip install tensorflow pip show tensorflow --ignore_installed pip install tensorflow==2.0.0-rc0 conda install -c conda-forge tensorflow conda install tensorflow pip3 show tensorflo...

Solutions tried:

pip install tensorflow

pip show tensorflow —ignore_installed

pip install tensorflow==2.0.0-rc0

conda install -c conda-forge tensorflow

conda install tensorflow

pip3 show tensorflow

pip show tensorflow
Note: you may need to restart the kernel to use updated packages.
WARNING: Package(s) not found: tensorflow
Tried restarting kernel.
Tried restarting laptop

Code trying to run:
from keras.models import load_model

Error:
runcell(0, ‘C:/Users/chinm/untitled1.py’)
Traceback (most recent call last):

File «C:Userschinmanaconda3libsite-packageskeras_init_.py», line 3, in
from tensorflow.keras.layers.experimental.preprocessing import RandomRotation

ModuleNotFoundError: No module named ‘tensorflow’

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File «C:Userschinmuntitled1.py», line 14, in
from keras.models import load_model

File «C:Userschinmanaconda3libsite-packageskeras_init_.py», line 6, in
‘Keras requires TensorFlow 2.2 or higher. ‘

ImportError: Keras requires TensorFlow 2.2 or higher. Install TensorFlow via pip install tensorflow

System information

  • OS Platform and Distribution : Windows 10 64-bits
  • TensorFlow installed from (source or binary): Python 3.6 CPU-only | https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.13.1-cp36-cp36m-win_amd64.whl
  • TensorFlow version: 1.13.1
  • Python version: 3.6.8
  • Installed using virtualenv? pip? conda?: conda

Describe the problem

Hi,
I have struggled for hours to install tensorflow to Anaconda and finally succeeded. Hope my experience can help those who have same problem with installation.

I have tried a lot of methods before, such as:

pip install tensorflow
conda install tensorflow

etc,.
These methods might act as it installed properly but when I tested it in spyder, there were some problems, such as:

ImportError: cannot import name ‘abs’
attributeerror: module ‘tensorflow’ has no attribute ‘version

I just installed tensorflow successfully in Anaconda following the instructions from: https://www.tensorflow.org/install/pip
2. Create a virtual environment (recommended)

(base) C:UsersXXXX>conda create -n venv pip python=3.6
(base) C:UsersXXXX>conda activate venv
(venv) C:UsersXXXX>pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.13.1-cp36-cp36m-win_amd64.whl

Then I test it in terminal:

(venv) C:UsersXXXX>python
Python 3.6.8 |Anaconda, Inc.| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> tf.__version__
'1.13.1'

It works!
But when I tried to import tensorflow in spyder:

ModuleNotFoundError: No module named ‘tensorflow’

Solution

This problem might cause by using virtual environment, and in Anaconda, your spyder or Jupyter Notebook works in default root, but tensorflow is installed in an isolated virtual environment ‘venv’. So just install a new spyder or Jupyter Notebook under the virtual enviroment.

Python is known for its versatile syntax and English-like keywords. With thousands of modules, you can do data visualization, data processing and even deploy machine learning models. There are many known machine learning models published which help you, namely, Keras, Sklearn, Tensorflow, and PyTorch. Although, while using Tensorflow, you can encounter a No Module named Tensorflow error while running your first program.

No Module Named Tensorflow Error is a known error that arises when the Python Environment is unable to fetch TensorFlow files in site-packages. There are two main reasons for this error to appear, either you have not installed the TensorFlow external module or you are working on a different python environment that doesn’t have Tensorflow. There are several easy ways to fix this error which are mentioned later in this post. Let’s understand the root cause of the error before jumping on the solution.

No Module Named Tensorflow Error

When a module is absent from the external site-library of the environment, the Python interpreter throws ModuleNotFoundError No Module Named Tensorflow. This error arises most of the time on low-end devices because TensorFlow requires proper setup of the c++ path and other requirements. Most of the time, this error is solved by using the pip install method. But if you have multiple Python versions installed, then you’ll definitely face this error.

Why do I get No Module Named Tensorflow Error?

There is no other reason for the No Module Named Tensorflow error other than missing module files. The main problem arises when you’re using multiple python versions and their virtual environment. Keep in mind that, Anaconda, PyCharm, Jupyter, and Spyder have their own virtual environment and it’s tricky to install modules in that environment.

Causes of No Module Named Tensorflow Error

There are some known causes of this ModuleNotFoundError. As Python lets you handle these errors easily, you can debug them quickly. Following are the cause of the No Module Tensorflow error –

Module Not Installed

If you haven’t installed TensorFlow yet and tried importing TensorFlow in code, then it’ll throw this error. Modules are managed by ‘pip’ which is a package management system for your python. Most of the time, the users forget to tick Add Python to the PATH option while installing it. This creates problems in managing the modules.

Supporting Module Not Installed

Tensorflow has many other supporting modules like numpy, scipy, jupyter, matplotlib, pillow, and scikit-learn. If any of these modules is absent, then it’ll throw an error. Make sure that these modules exist in your library.

Moreover, there are other supporting TensorFlow modules like, tensorflow-addons, tensorflow.contrib which might be absent from your library leading to this error.

Tip: To check which libraries are installed in your environment, enter pip list on your console.

Working on Different Virtual Environment

Virtual Environment: Method by which you isolate your working Python environment from the globally installed Python. This environment has its own installation directories and doesn’t share the libraries from globally installed Python.

Many of the code editors in Windows come with their own virtual environment. Each of these environments acts independently to global python installation and is started with blank external modules. Many times, you install a module but it’s installed on global python, not the python from your virtual environment. This can lead to ModuleNotFoundError No Module named Tensorflow in the code execution.

Code editors namely, Anaconda, Jupyter, and Spyder have their own virtual environment. If you have a similar case, head over to the corresponding solution for each code editor.

Solutions for No Module Named Tensorflow

Following are the solutions for this error in each code editor and OS –

Windows

No Module Tensorflow Windows

In Windows, the path-related issues harras the programmers all the time. As you have limited functionality over the terminal, you’re constantly facing with ModuleNotFoundError error. To install TensorFlow in your Windows, make sure you follow these steps –

  1. Uninstall existing python versions to avoid any conflicts.
  2. Go to Python.org and install the Python setup. Make sure you install the 64-bit version. Unfortunately, Tensorflow is not supported in 32 bit systems.
  3. Open the installer and select the “Add Python x.x to your PATH” option. This will ensure, that python executes from the path.
  4. After installing, open the command terminal or PowerShell and enter the command pip install tensorflow in it.
  5. Wait for it to finish the installation and run your python file by command python file.py

Linux

In Linux, it’s relatively easier to install TensorFlow. First of all, check if you are working on a virtual environment by a command which python. This command will return the path of python which you’re going to execute. If you are in a virtual environment, either leave the environment directory or enter the command deactivate to deactivate the virtual environment.

Note: Please do not try to uninstall python in Linux as it’ll interfere with your GDM (Graphical Display Manager). Instead, install a new version and then create your own virtual environment.

Follow these steps to install Tensorflow in Linux –

sudo pip3 install tensorflow

Mac

In Mac, No Module named Tensorflow is a persistent error because of environment errors. If you are working on your virtual environment, you need to deactivate and activate it again. Then use the pip list command to check if the TensorFlow module exists in your library. If not, then use the pip3 install tensorflow to install TensorFlow.

Anaconda

No Module Named Tensorflow in Anaconda

If you’re using Anaconda and you face no module named Tensorflow error, then you probably haven’t installed TensorFlow in the conda environment. As anaconda has a different environment than your default python environment, you need to install TensorFlow in it. To do it follow these steps –

  1. Open Anaconda Prompt on your computer.
  2. Enter the command conda install tensorflow in it.
  3. Wait for the installation to complete and restart the conda shell and run your program.

Jupyter

If you’ve installed Juptyter Notebook from Anaconda, it’ll use a conda environment. By default, the libraries in this environment need to be installed via command. To do the same, open your Conda Prompt and enter the command conda install tensorflow. This will ensure that your Juptyer Notebook has TensorFlow in it.

If your Jupyter is not installed via Anaconda, then use the pip install tensorflow to install the TensorFlow module. This will resolve the error ModuleNotFoundError No module named Tensorflow instantly.

Spyder

Spyder is installed via Anaconda which operates an Anaconda environment. Simply use the command conda install tensorflow in your Anaconda Prompt to install TensorFlow.

PyCharm

PyCharm is a special application that operates in its own virtual environment. Due to the unavailability of the TensorFlow error, you can face the no module found error. Follow these steps to install TensorFlow –

  1. Press Settings and select the Project Interpreter tab under projects.
  2. Now enter Tensorflow in the box and install it.
  3. After installing the package, your error will be resolved.

Supporting ModuleNotFoundError for Tensorflow

Tensorflow has many addons which come in handy to avoid writing long code. These addons and contributions are added separately in other packages and combine with the original TensorFlow module. Following are the examples of ModuleNotFoundError –

No module named ‘tensorflow.contrib’

Unfortunately, the contrib module in TensorFlow is not included in version 2.0. If you still want to use the contrib module, you’ll have to install the previous version of TensorFlow. Follow these steps –

pip uninstall tensorflow
pip install tensorflow==1.13.2

No module named ‘tensorflow_addons’

Use pip install tensorflow-addons to install the addons for TensorFlow.

No Module Named Tensorflow Still Not Resolved?

If you’ve tried all the methods and were still not able to solve the issue then, there might be some hardware limitations. Tensorflow requires Python 3.5-3.7, 64-bit system, and pip>=19.0. If you’re unable to fulfill these hardware + software requirements, then don’t worry, we still have a solution for you!

Google released a free product named ‘Colab‘ in 2018. Colab allows you to run and test machine learning models online. To explain more, it’s a replica of the jupyter notebook with all modules installed. To use Tensorflow in Google Colab follow these steps –

  1. Sign in to your Google account.
  2. Open Colab in your browser.
  3. Create a new Jupyter Notebook. (This notebook will be saved in your google drive).
  4. Type your code and run it.

Using Tensorflow in Colab

Colab has many libraries like TensorFlow, numpy, pandas, etc pre-installed in its shell. Make sure you make good use of it.

Tip: Do not use Colab to store/process peer-to-peer files. This may result in a ban!

See Also

Conclusion

Tensor flow has a flexible architecture. The easy deployment of the code makes it special in nature. However, we have to be very careful before using it. Any small syntax error can result in incorrect importing of the library.

The “ModuleNotFoundError: No module named ‘tensorflow’” error in Python shows that Python cannot find the module ‘tensorflow’ that is imported in your code or some packages your code imports. This tutorial will show you how to fix the error by installing ‘tensorflow’ in your environment.

When you run your Python code, the Python runtime will look for all the packages or modules you import to your code and their dependencies. If the runtime cannot find a module, it will throw a ModuleNotFoundError. The error “ModuleNotFoundError: No module named ‘tensorflow’” show that Python cannot find ‘tensorflow’ in your environment, so you need to install it to run your code correctly. Here I have an example code that imports ‘tensorflow’ and prints its version. You will get the error if you run this code in a Python environment without ‘tensorflow’ installed.

Example code:

import tensorflow as tf
print("Tensorflow version:", tf.__version__)

Output:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'

How to solve the error?

Method 1: Install tensorflow directly with pip

Pip is the package installer for Python that comes with Python when you install Python on your machine. You can check the version of pip by the following command in your terminal of Linux/MacOS or the Command prompt of Windows. 

pip --version

Output:

pip 21.1.3 from <the path where pip installed on your machine>

To install ‘tensorflow’ using pip, you can easily run this command.

pip install tensorflow

You can also specify the ‘tensorflow’ version that you want to install like this.

pip install tensorflow==2.10.0

After successfully installing ‘tensorflow’, you can use it in your code as you want.

Example code:

import tensorflow as tf
print("Tensorflow version:", tf.__version__)

Output:

Tensorflow version: 2.10.0

Method 2: Install tensorflow in a python virtual environment

It is recommended to install the packages that you need for different projects in different environments because you may want to use different versions of a package in your projects. Using different environments helps to keep the packages not conflict with each other. You can create and activate a virtual environment by the following steps.

  • Step 1: Install virtualenv package
pip install virtualenv
  • Step 2: Create the environment folder where the packages will be installed
python -m venv env
  • Step 3: Activate the environment

On Linux/MacOS:

source env/bin/activate

On Windows:

cd env/Scripts
activate.bat

Step 2 will create an environment folder name env in the directory where you run the command. After activating your environment, you can normally install ‘tensorflow’ using the pip command: 

pip install tensorflow

Method 3: Install tensorflow using conda

Another way to create python environments is using conda. You can download and install the conda by following this instruction. After installing conda, you can create a new environment by the command:

conda create -n myenv python

Then, you can activate your environment:

conda activate myenv

Finally, you can install ‘tensorflow’ using pip or conda if you want.

conda install -c conda-forge tensorflow

Summary

In this tutorial, I’ve showed you how to solve the error  “ModuleNotFoundError: No module named ‘tensorflow’” In Python. You can install ‘tensorflow’ directly with pip, but it is recommended to create an environment by the Python virtualenv or conda.

Maybe you are interested in similar errors:

  • No module named ‘pkg_resources’ in Python
  • How To ModuleNotFoundError: No Module Named ‘absl’ In Python

Hello, I’m Joseph Stanley. My major is IT and I want to share programming languages to you. If you have difficulty with JavaScript, TypeScript, C#, Python, C, C++, Java, let’s follow my articles. They are helpful for you.


Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: JavaScript, TypeScript, C#, Python, C, C++, Java

TensorFlow uses GitHub issues,
Stack Overflow and
TensorFlow Forum
to track, document, and discuss build and installation problems.

The following list links error messages to a solution or discussion. If you find
an installation or build problem that is not listed, please search the GitHub
issues and Stack Overflow. If you still can’t find the error message, ask a new
question on Stack Overflow with the tensorflow tag.

GitHub issue or Stack Overflow Error Message
38896424
31058
«No matching distribution found for tensorflow»:
Pip can’t find a TensorFlow package compatible with your system. Check the
system requirements and
Python version
22390
Unzipping simple_console_for_windows.zip to create runfiles tree...
[./bazel-bin/tensorflow/tools/pip_package/simple_console_for_windows.zip]
  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip: cannot find zipfile directory in one of ./bazel-bin/tensorflow/tools/pip_package/simple_console_for_windows.zip or
        ./bazel-bin/tensorflow/tools/pip_package/simple_console_for_windows.zip.zip, and cannot find ./bazel-bin/tensorflow/tools/pip_package/simple_console_for_windows.zip.ZIP, period.
36159194
ImportError: libcudart.so.Version: cannot open shared object file:
  No such file or directory
41991101
ImportError: libcudnn.Version: cannot open shared object file:
  No such file or directory
36371137
libprotobuf ERROR google/protobuf/src/google/protobuf/io/coded_stream.cc:207] A
  protocol message was rejected because it was too big (more than 67108864 bytes).
  To increase the limit (or to disable these warnings), see
  
CodedInputStream::SetTotalBytesLimit() in google/protobuf/io/coded_stream.h.
35252888
Error importing tensorflow. Unless you are using bazel, you should
  not try to import tensorflow from its source directory; please exit the
  tensorflow source tree, and relaunch your python interpreter from
  there.
33623453
IOError: [Errno 2] No such file or directory:
  '/tmp/pip-o6Tpui-build/setup.py'
42006320
ImportError: Traceback (most recent call last):
  File ".../tensorflow/core/framework/graph_pb2.py", line 6, in 
  from google.protobuf import descriptor as _descriptor
  ImportError: cannot import name 'descriptor'
35190574
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify
  failed
42009190
  Installing collected packages: setuptools, protobuf, wheel, numpy, tensorflow
  Found existing installation: setuptools 1.1.6
  Uninstalling setuptools-1.1.6:
  Exception:
  ...
  [Errno 1] Operation not permitted:
  '/tmp/pip-a1DXRT-uninstall/.../lib/python/_markerlib' 
36933958
  ...
  Installing collected packages: setuptools, protobuf, wheel, numpy, tensorflow
  Found existing installation: setuptools 1.1.6
  Uninstalling setuptools-1.1.6:
  Exception:
  ...
  [Errno 1] Operation not permitted:
  '/tmp/pip-a1DXRT-uninstall/System/Library/Frameworks/Python.framework/
   Versions/2.7/Extras/lib/python/_markerlib'
42006320
ImportError: Traceback (most recent call last):
File ".../tensorflow/core/framework/graph_pb2.py", line 6, in 
from google.protobuf import descriptor as _descriptor
ImportError: cannot import name 'descriptor'
33623453
IOError: [Errno 2] No such file or directory:
  '/tmp/pip-o6Tpui-build/setup.py'
35190574
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify
  failed
42009190
  Installing collected packages: setuptools, protobuf, wheel, numpy, tensorflow
  Found existing installation: setuptools 1.1.6
  Uninstalling setuptools-1.1.6:
  Exception:
  ...
  [Errno 1] Operation not permitted:
  '/tmp/pip-a1DXRT-uninstall/.../lib/python/_markerlib' 
33622019
ImportError: No module named copyreg
37810228 During a pip install operation, the system returns:

OSError: [Errno 1] Operation not permitted
33622842 An import tensorflow statement triggers an error such as the
following:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.7/site-packages/tensorflow/__init__.py",
    line 4, in 
    from tensorflow.python import *
    ...
  File "/usr/local/lib/python2.7/site-packages/tensorflow/core/framework/tensor_shape_pb2.py",
    line 22, in 
    serialized_pb=_b('n,tensorflow/core/framework/tensor_shape.protox12ntensorflow"dnx10TensorShapeProtox12-nx03x64imx18x02
      x03(x0bx32
      .tensorflow.TensorShapeProto.Dimx1a!nx03x44imx12x0cnx04sizex18x01
      x01(x03x12x0cnx04namex18x02 x01(tbx06proto3')
  TypeError: __init__() got an unexpected keyword argument 'syntax'
42075397 A pip install command triggers the following error:

...
You have not agreed to the Xcode license agreements, please run
'xcodebuild -license' (for user-level acceptance) or
'sudo xcodebuild -license' (for system-wide acceptance) from within a
Terminal window to review and agree to the Xcode license agreements.
...
  File "numpy/core/setup.py", line 653, in get_mathlib_info

    raise RuntimeError("Broken toolchain: cannot link a simple C program")

RuntimeError: Broken toolchain: cannot link a simple C program
41007279
[...stream_executordso_loader.cc] Couldn't open CUDA library nvcuda.dll
41007279
[...stream_executorcudacuda_dnn.cc] Unable to load cuDNN DSO
42006320
ImportError: Traceback (most recent call last):
File "...tensorflowcoreframeworkgraph_pb2.py", line 6, in 
from google.protobuf import descriptor as _descriptor
ImportError: cannot import name 'descriptor'
42011070
No module named "pywrap_tensorflow"
42217532
OpKernel ('op: "BestSplits" device_type: "CPU"') for unknown op: BestSplits
43134753
The TensorFlow library wasn't compiled to use SSE instructions
38896424
Could not find a version that satisfies the requirement tensorflow
42006320
ImportError: Traceback (most recent call last):
File ".../tensorflow/core/framework/graph_pb2.py", line 6, in 
from google.protobuf import descriptor as _descriptor
ImportError: cannot import name 'descriptor'
33623453
IOError: [Errno 2] No such file or directory:
  '/tmp/pip-o6Tpui-build/setup.py'
35190574
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify
  failed
42009190
  Installing collected packages: setuptools, protobuf, wheel, numpy, tensorflow
  Found existing installation: setuptools 1.1.6
  Uninstalling setuptools-1.1.6:
  Exception:
  ...
  [Errno 1] Operation not permitted:
  '/tmp/pip-a1DXRT-uninstall/.../lib/python/_markerlib' 
33622019
ImportError: No module named copyreg
37810228 During a pip install operation, the system returns:

OSError: [Errno 1] Operation not permitted
33622842 An import tensorflow statement triggers an error such as the
following:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.7/site-packages/tensorflow/__init__.py",
    line 4, in 
    from tensorflow.python import *
    ...
  File "/usr/local/lib/python2.7/site-packages/tensorflow/core/framework/tensor_shape_pb2.py",
    line 22, in 
    serialized_pb=_b('n,tensorflow/core/framework/tensor_shape.protox12ntensorflow"dnx10TensorShapeProtox12-nx03x64imx18x02
      x03(x0bx32
      .tensorflow.TensorShapeProto.Dimx1a!nx03x44imx12x0cnx04sizex18x01
      x01(x03x12x0cnx04namex18x02 x01(tbx06proto3')
  TypeError: __init__() got an unexpected keyword argument 'syntax'
41293077
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow
  library wasn't compiled to use SSE4.1 instructions, but these are available on
  your machine and could speed up CPU computations.
42013316
ImportError: libcudart.so.8.0: cannot open shared object file:
  No such file or directory
42013316
ImportError: libcudnn.5: cannot open shared object file:
  No such file or directory
35953210 Invoking `python` or `ipython` generates the following error:

ImportError: cannot import name pywrap_tensorflow
45276830
external/local_config_cc/BUILD:50:5: in apple_cc_toolchain rule
  @local_config_cc//:cc-compiler-darwin_x86_64: Xcode version must be specified
  to use an Apple CROSSTOOL.
47080760
undefined reference to `cublasGemmEx@libcublas.so.9.0'
22512
ModuleNotFoundError: No module named 'tensorflow.python._pywrap_tensorflow_internal'
22512, 22794
ImportError: DLL load failed: The specified module could not be found.
24835
Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: [long path name]

In this Python tutorial, we will discuss the error “import error no module named TensorFlow. Here we’ll cover the reason related to this error using Python. And we’ll also cover the following topics:

  • Import error no module named tensorflow.compat.v1
  • Import error no module named ‘tensorflow.contrib’
  • Import error no module named tensorflow_hub
  • Import error no module named ‘tensorflow addons’
  • Import error no module named ‘tensorflow.python.eager’
  • In this section, we will discuss the error import error no module named TensorFlow in Python.
  • Basically, this error message comes when we do not import the TensorFlow library or we can say the TensorFlow library is not installed in our system.
  • If you have not installed the TensorFlow library in your system and still want to try importing the TensorFlow library in your program then it will raise an error message ‘no module named TensorFlow.

Example:

import tensorflow as tf

tens1 = tf.Variable([[67, 89],[23, 45]])
tens2 = tf.Variable([[94, 117],[189, 210]])
new_output= tf.add(tens1,tens2)
print(new_output)

In the above code, we have used the tf.add() function and within this function, we assigned the given tensors ‘tens1’ and ‘tens2’ as an argument.

Here is the Screenshot of the following given code.

Python import error no module named TensorFlow
import error no module named TensorFlow

Now let’s see the solution for this error:

Visual Code Studio

If you have installed Visual code Studio then it will use a pip environment and if you want to import some needed libraries then you have to install via command.

  • install TensorFlow using pip command

Syntax:

Here is the Syntax of the installation of the TensorFlow library

pip install TensorFlow

This Syntax will help you to resolve the error ‘no Module named TensorFlow’

Jupyter

If you have installed Jupyter notebook then use the Conda environment. To get detailed information regarding how to install the TensorFlow library in the Conda environment. You can refer to our detailed article TensorFlow in Python.

Also, check: TensorFlow Sparse Tensor

Import error no module named ‘tensorflow.contrib’

  • Here we are going to discuss the error import error no module named ‘TensorFlow.contrib’.
  • Basically, the contrib module is not available in TensorFlow version 2.0. This module contains contributed code and it is also a volatile code.
  • The possible reason behind this error is when the interpreter cannot locate the contrib ‘module’ in the library.
  • The latest version of TensorFlow 2.x has removed the session and contrib module from the TensorFlow library.

Reason: module ‘contrib’ is not working in version 2.x

Example:

import tensorflow.contrib

Here is the Screenshot of the following given code

import error no module named 'tensorflow.contrib'
import error no module named ‘TensorFlow.contrib’

In the following given code, we have just imported the ‘TensorFlow.contrib’ module but when we executed this command it displays the No module named ‘TensorFlow.contrib’. The possible reason is this module does not work in the latest version of TensorFlow 2.x.

Let’s discuss the solution to this error

  • First, uninstall the already installed version, if it is the latest version then reinstall it with the older version. To uninstall the tensorflow 2.x you can easily use the command pip uninstall TensorFlow.
  • Now to install older version of TensorFlow 1.x you can use below command
pip install tensorflow==1.15.0

Read: Python TensorFlow reduce_sum

Import error no module named tensorflow.compat.v1

  • In this section, we are going to discuss the error no module named tensorflow.compat.v1.
  • The possible reason behind this error is that compat.v1 modules are deprecated in Tensorflow version 1.12.0. This module will help the user to write the code in both TensorFlow versions.
  • This module does not support the 1.12 version, if you want to execute this module on your system then you have to install the latest or above the 1.12 version.

Example:

import error no module named tensorflow compat v1 in Python
import error no module named TensorFlow compat v1 in Python

Now we are going to use the updated version of TensorFlow for importing the TensorFlow.compat.v1 module in Python

To install the new version of TensorFlow in Conda prompt you can use the below command

conda install tensorflow==2.6
Solution of no module named tensorflow compat v1 in Python
Solution of no module named TensorFlow compat v1 in Python

As you can see in the Screenshot we have checked the version of TensorFlow it displays 2.6 latest version and also successfully imported the TensorFlow.compat.v1.

Also, check: Module ‘TensorFlow’ has no attribute ‘session’

Import error no module named ‘tensorflow_hub’

  • In this Program, we will discuss the error no module named ‘tensorflow_hub’ in Python.
  • Basically, this error message comes when the module ‘tensorflow_hub’ is not available in the TensorFlow library package.

Example:

Python import error no module named tensorflow hub
Python import error no module named TensorFlow hub

As you can see in the Screenshot it displays no module name ‘tensorflow_hub’ the reason behind this is we are using the older version of TensorFlow 1.14. In this version, the tensorflow_hub module is not working.

Let’s have a look at the Solution to this error

To solve this error you have to install the latest version of TensorFlow in your system. By default 2.7 is a stable version and to install the updated version of TensorFlow, you can use the below command. This command is used for conda prompt users.

conda install tensorflow==2.7

Screenshot

Solution of import error no module named tensorflow hub
Solution of import error no module named TensorFlow hub

In this Screenshot, you can see that we have installed the latest version of TensorFlow 2.7 and then import the tensorflow_hub module.

Read: TensorFlow Tensor to numpy

Import error no module named ‘tensorflow addons’

  • In this section, we will discuss the error no module named ‘tensorflow addons’ in Python.
  • Basically, the addon module is available in the latest TensorFlow version 2.7 but we have to update the ‘TensorFlow addons’ module. This module is not available in core Tensorflow and it also supports optimizers, metrics, and losses.

Screenshot

import error no module named tensorflow addons
import error no module named TensorFlow addons

As you can see in the output, it displays no module name ‘tensorflow_addons’. And the possible reason is that the ‘tensorflow_addons‘ module is available in TensorFlow latest version 2.7. But we have to update the ‘tensorflow_addons’ module.

Let’s have a look at the Solution to this error

To solve this error you have to install the older version of TensorFlow in your system. By default 2.7 is a stable version but this module only does not work in the latest version 2.x.

Output:

Solution of import error no module named tensorflow addons
Solution of import error no module named TensorFlow addons

To upgrade the ‘TensorFlow addons’ module you can easily use the below command

pip install tensorflow-addons

In the above code, we have imported the tensorflow_addons() module after upgrading the module.

Read: TensorFlow global average pooling

Import error no module named ‘tensorflow.python.eager’

  • Here we are going to discuss the error no module named ‘tensorflow.python.eager’ in Python.
  • When I was trying to import the ‘TensorFlow.python.eager’ module this error comes out in output. The reason behind that is the version of the TensorFlow library.

Let’s have a look at the Solution to this error

In this example, we have just imported the TensorFlow library and then checked the version by using the tf.__version__ command. After that, we have imported the ‘tensorflow.python.eager’ module. Once you will execute this code the output displays the module has been successfully imported.

Example:

import error no module named tensorflow python eager
import error no module named tensorflow python eager

Also, take a look at some more Python TensorFlow tutorials.

  • Binary Cross Entropy TensorFlow
  • Gradient descent optimizer TensorFlow
  • Python TensorFlow Placeholder
  • Convert list to tensor TensorFlow
  • Module ‘tensorflow’ has no attribute ‘div’
  • Module ‘tensorflow’ has no attribute ‘sparse_placeholder’

So, in this tutorial, we have solved the error “import error no module named TensorFlow“. Here we’ll cover the reason related to this error using Python. And we’ll also cover the following topics:

  • import error no module named tensorflow.compat.v1
  • import error no module named ‘tensorflow.contrib’
  • import error no module named tensorflow_hub
  • import error no module named ‘tensorflow addons’
  • import error no module named ‘tensorflow.python.eager’

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

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!

Quick Fix: Python raises the ImportError: No module named 'tensorflow' when it cannot find the library tensorflow. The most frequent source of this error is that you haven’t installed tensorflow explicitly with pip install tensorflow. Alternatively, you may have different Python versions on your computer, and tensorflow is not installed for the particular version you’re using.

Problem Formulation

You’ve just learned about the awesome capabilities of the tensorflow library and you want to try it out, so you start your code with the following statement:

import tensorflow

This is supposed to import the Pandas library into your (virtual) environment. However, it only throws the following ImportError: No module named tensorflow:

>>> import tensorflow
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    import tensorflow
ModuleNotFoundError: No module named 'tensorflow'

Solution Idea 1: Install Library tensorflow

The most likely reason is that Python doesn’t provide tensorflow in its standard library. You need to install it first!

Before being able to import the Pandas module, you need to install it using Python’s package manager pip. Make sure pip is installed on your machine.

To fix this error, you can run the following command in your Windows shell:

$ pip install tensorflow

This simple command installs tensorflow in your virtual environment on Windows, Linux, and MacOS. It assumes that your pip version is updated. If it isn’t, use the following two commands in your terminal, command line, or shell (there’s no harm in doing it anyways):

$ python -m pip install --upgrade pip
$ pip install pandas

💡 Note: Don’t copy and paste the $ symbol. This is just to illustrate that you run it in your shell/terminal/command line.

Solution Idea 2: Fix the Path

The error might persist even after you have installed the tensorflow library. This likely happens because pip is installed but doesn’t reside in the path you can use. Although pip may be installed on your system the script is unable to locate it. Therefore, it is unable to install the library using pip in the correct path.

To fix the problem with the path in Windows follow the steps given next.

Step 1: Open the folder where you installed Python by opening the command prompt and typing where python

Step 2: Once you have opened the Python folder, browse and open the Scripts folder and copy its location. Also verify that the folder contains the pip file.

Step 3: Now open the Scripts directory in the command prompt using the cd command and the location that you copied previously.

Step 4: Now install the library using pip install tensorflow command. Here’s an analogous example:

After having followed the above steps, execute our script once again. And you should get the desired output.

Other Solution Ideas

  • The ModuleNotFoundError may appear due to relative imports. You can learn everything about relative imports and how to create your own module in this article.
  • You may have mixed up Python and pip versions on your machine. In this case, to install tensorflow for Python 3, you may want to try python3 -m pip install tensorflow or even pip3 install tensorflow instead of pip install tensorflow
  • If you face this issue server-side, you may want to try the command pip install --user tensorflow
  • If you’re using Ubuntu, you may want to try this command: sudo apt install tensorflow
  • You can check out our in-depth guide on installing tensorflow here.
  • You can also check out this article to learn more about possible problems that may lead to an error when importing a library.

Understanding the “import” Statement

import tensorflow

In Python, the import statement serves two main purposes:

  • Search the module by its name, load it, and initialize it.
  • Define a name in the local namespace within the scope of the import statement. This local name is then used to reference the accessed module throughout the code.

What’s the Difference Between ImportError and ModuleNotFoundError?

What’s the difference between ImportError and ModuleNotFoundError?

Python defines an error hierarchy, so some error classes inherit from other error classes. In our case, the ModuleNotFoundError is a subclass of the ImportError class.

You can see this in this screenshot from the docs:

You can also check this relationship using the issubclass() built-in function:

>>> issubclass(ModuleNotFoundError, ImportError)
True

Specifically, Python raises the ModuleNotFoundError if the module (e.g., tensorflow) cannot be found. If it can be found, there may be a problem loading the module or some specific files within the module. In those cases, Python would raise an ImportError.

If an import statement cannot import a module, it raises an ImportError. This may occur because of a faulty installation or an invalid path. In Python 3.6 or newer, this will usually raise a ModuleNotFoundError.

Related Videos

The following video shows you how to resolve the ImportError:

How to Fix : “ImportError: Cannot import name X” in Python?

The following video shows you how to import a function from another folder—doing it the wrong way often results in the ModuleNotFoundError:

How to Call a Function from Another File in Python?

How to Fix “ModuleNotFoundError: No module named ‘tensorflow’” in PyCharm

If you create a new Python project in PyCharm and try to import the tensorflow library, it’ll raise the following error message:

Traceback (most recent call last):
  File "C:/Users/.../main.py", line 1, in <module>
    import tensorflow
ModuleNotFoundError: No module named 'tensorflow'

Process finished with exit code 1

The reason is that each PyCharm project, per default, creates a virtual environment in which you can install custom Python modules. But the virtual environment is initially empty—even if you’ve already installed tensorflow on your computer!

Here’s a screenshot exemplifying this for the pandas library. It’ll look similar for tensorflow.

The fix is simple: Use the PyCharm installation tooltips to install Pandas in your virtual environment—two clicks and you’re good to go!

First, right-click on the pandas text in your editor:

Second, click “Show Context Actions” in your context menu. In the new menu that arises, click “Install Pandas” and wait for PyCharm to finish the installation.

The code will run after your installation completes successfully.

As an alternative, you can also open the Terminal tool at the bottom and type:

$ pip install tensorflow

If this doesn’t work, you may want to set the Python interpreter to another version using the following tutorial: https://www.jetbrains.com/help/pycharm/2016.1/configuring-python-interpreter-for-a-project.html

You can also manually install a new library such as tensorflow in PyCharm using the following procedure:

  • Open File > Settings > Project from the PyCharm menu.
  • Select your current project.
  • Click the Python Interpreter tab within your project tab.
  • Click the small + symbol to add a new library to the project.
  • Now type in the library to be installed, in your example Pandas, and click Install Package.
  • Wait for the installation to terminate and close all popup windows.

Here’s an analogous example:

Here’s a full guide on how to install a library on PyCharm.

  • How to Install a Library on PyCharm

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Понравилась статья? Поделить с друзьями:
  • Modern setup host что это грузит диск windows 10
  • Modulenotfounderror no module named pil windows
  • Modern setup host при установке windows 10
  • Modulenotfounderror no module named matplotlib windows
  • Modern setup host ошибка обновления windows