Import tensorflow as tf error

installed from anaconda using pip install tensorflow OS Platform: Windows 7 64bit intel processor intel hd graphic graphic card python version 3.6.4 Have I written custom code: No Bazel version : I...

installed from anaconda using
pip install tensorflow

OS Platform:
Windows 7 64bit
intel processor
intel hd graphic graphic card
python version 3.6.4

Have I written custom code: No
Bazel version : I don’t have
CUDA/cuDNN version : I don’t have
GPU model and memory :NA
Exact command to reproduce : import tensorflow as tf using jupyter

(base) C:Usersdavid>pip install tensorflow
Collecting tensorflow
  Downloading https://files.pythonhosted.org/packages/f4/88/980d7032b7408fcca5b0
b8d420fcd97919197a9e7acf280ab74fc7db6993/tensorflow-1.8.0-cp36-cp36m-win_amd64.w
hl (34.4MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 34.4MB 13kB/s
Collecting astor>=0.6.0 (from tensorflow)
  Downloading https://files.pythonhosted.org/packages/b2/91/cc9805f1ff7b49f62013
6b3a7ca26f6a1be2ed424606804b0fbcf499f712/astor-0.6.2-py2.py3-none-any.whl
Collecting gast>=0.2.0 (from tensorflow)
  Downloading https://files.pythonhosted.org/packages/5c/78/ff794fcae2ce8aa6323e
789d1f8b3b7765f601e7702726f430e814822b96/gast-0.2.0.tar.gz
Requirement already satisfied: six>=1.10.0 in c:programdataanaconda3libsite-
packages (from tensorflow)
Collecting tensorboard<1.9.0,>=1.8.0 (from tensorflow)
  Downloading https://files.pythonhosted.org/packages/59/a6/0ae6092b7542cfedba6b
2a1c9b8dceaf278238c39484f3ba03b03f07803c/tensorboard-1.8.0-py3-none-any.whl (3.1
MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 3.1MB 682kB/s
Requirement already satisfied: numpy>=1.13.3 in c:programdataanaconda3libsit
e-packages (from tensorflow)
Collecting termcolor>=1.1.0 (from tensorflow)
  Downloading https://files.pythonhosted.org/packages/8a/48/a76be51647d0eb9f10e2
a4511bf3ffb8cc1e6b14e9e4fab46173aa79f981/termcolor-1.1.0.tar.gz
Requirement already satisfied: wheel>=0.26 in c:programdataanaconda3libsite-
packages (from tensorflow)
Collecting grpcio>=1.8.6 (from tensorflow)
  Downloading https://files.pythonhosted.org/packages/80/7e/d5ee3ef92822b01e3a27
4230200baf2454faae64e3d7f436b093ff771a17/grpcio-1.11.0-cp36-cp36m-win_amd64.whl
(1.4MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 1.4MB 787kB/s
Collecting protobuf>=3.4.0 (from tensorflow)
  Downloading https://files.pythonhosted.org/packages/32/cf/6945106da76db9b62d11
b429aa4e062817523bb587018374c77f4b63200e/protobuf-3.5.2.post1-cp36-cp36m-win_amd
64.whl (958kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 962kB 787kB/s
Collecting absl-py>=0.1.6 (from tensorflow)
  Downloading https://files.pythonhosted.org/packages/90/6b/ba04a9fe6aefa56adafa
6b9e0557b959e423c49950527139cb8651b0480b/absl-py-0.2.0.tar.gz (82kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 92kB 708kB/s
Collecting bleach==1.5.0 (from tensorboard<1.9.0,>=1.8.0->tensorflow)
  Downloading https://files.pythonhosted.org/packages/33/70/86c5fec937ea4964184d
4d6c4f0b9551564f821e1c3575907639036d9b90/bleach-1.5.0-py2.py3-none-any.whl
Requirement already satisfied: werkzeug>=0.11.10 in c:programdataanaconda3lib
site-packages (from tensorboard<1.9.0,>=1.8.0->tensorflow)
Collecting markdown>=2.6.8 (from tensorboard<1.9.0,>=1.8.0->tensorflow)
  Downloading https://files.pythonhosted.org/packages/6d/7d/488b90f470b96531a3f5
788cf12a93332f543dbab13c423a5e7ce96a0493/Markdown-2.6.11-py2.py3-none-any.whl (7
8kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 81kB 682kB/s
Collecting html5lib==0.9999999 (from tensorboard<1.9.0,>=1.8.0->tensorflow)
  Downloading https://files.pythonhosted.org/packages/ae/ae/bcb60402c60932b32dfa
f19bb53870b29eda2cd17551ba5639219fb5ebf9/html5lib-0.9999999.tar.gz (889kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 890kB 787kB/s
Requirement already satisfied: setuptools in c:programdataanaconda3libsite-p
ackages (from protobuf>=3.4.0->tensorflow)
Building wheels for collected packages: gast, termcolor, absl-py, html5lib
  Running setup.py bdist_wheel for gast ... done
  Stored in directory: C:UsersdavidAppDataLocalpipCachewheels9a1fe3c
de98113222b853e98fc0a8e9924480a3e25f1b4008cedb4f
  Running setup.py bdist_wheel for termcolor ... done
  Stored in directory: C:UsersdavidAppDataLocalpipCachewheels7c654bc
84598ba1daf8f970247f550b175aaaee85f68b4b0c5ab2c6
  Running setup.py bdist_wheel for absl-py ... done
  Stored in directory: C:UsersdavidAppDataLocalpipCachewheels23351d48
c0a173ca38690dd8dfccfa47ffc750db48f8989ed898455c
  Running setup.py bdist_wheel for html5lib ... done
  Stored in directory: C:UsersdavidAppDataLocalpipCachewheels50aef9d2
b189788efcf61d1ee0e36045476735c838898eef1cad6e29
Successfully built gast termcolor absl-py html5lib
Installing collected packages: astor, gast, html5lib, bleach, markdown, protobuf
, tensorboard, termcolor, grpcio, absl-py, tensorflow
  Found existing installation: html5lib 1.0.1
    Uninstalling html5lib-1.0.1:
      Successfully uninstalled html5lib-1.0.1
  Found existing installation: bleach 2.1.2
    Uninstalling bleach-2.1.2:
      Successfully uninstalled bleach-2.1.2
Successfully installed absl-py-0.2.0 astor-0.6.2 bleach-1.5.0 gast-0.2.0 grpcio-
1.11.0 html5lib-0.9999999 markdown-2.6.11 protobuf-3.5.2.post1 tensorboard-1.8.0
 tensorflow-1.8.0 termcolor-1.1.0
You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
C:ProgramDataAnaconda3libsite-packagestensorflowpythonpywrap_tensorflow_internal.py in swig_import_helper()
     13         try:
---> 14             return importlib.import_module(mname)
     15         except ImportError:

C:ProgramDataAnaconda3libimportlib__init__.py in import_module(name, package)
    125             level += 1
--> 126     return _bootstrap._gcd_import(name[level:], package, level)
    127 

C:ProgramDataAnaconda3libimportlib_bootstrap.py in _gcd_import(name, package, level)

C:ProgramDataAnaconda3libimportlib_bootstrap.py in _find_and_load(name, import_)

C:ProgramDataAnaconda3libimportlib_bootstrap.py in _find_and_load_unlocked(name, import_)

C:ProgramDataAnaconda3libimportlib_bootstrap.py in _load_unlocked(spec)

C:ProgramDataAnaconda3libimportlib_bootstrap.py in module_from_spec(spec)

C:ProgramDataAnaconda3libimportlib_bootstrap_external.py in create_module(self, spec)

C:ProgramDataAnaconda3libimportlib_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)

ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

ModuleNotFoundError                       Traceback (most recent call last)
C:ProgramDataAnaconda3libsite-packagestensorflowpythonpywrap_tensorflow.py in <module>()
     57 
---> 58   from tensorflow.python.pywrap_tensorflow_internal import *
     59   from tensorflow.python.pywrap_tensorflow_internal import __version__

C:ProgramDataAnaconda3libsite-packagestensorflowpythonpywrap_tensorflow_internal.py in <module>()
     16             return importlib.import_module('_pywrap_tensorflow_internal')
---> 17     _pywrap_tensorflow_internal = swig_import_helper()
     18     del swig_import_helper

C:ProgramDataAnaconda3libsite-packagestensorflowpythonpywrap_tensorflow_internal.py in swig_import_helper()
     15         except ImportError:
---> 16             return importlib.import_module('_pywrap_tensorflow_internal')
     17     _pywrap_tensorflow_internal = swig_import_helper()

C:ProgramDataAnaconda3libimportlib__init__.py in import_module(name, package)
    125             level += 1
--> 126     return _bootstrap._gcd_import(name[level:], package, level)
    127 

ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-306-64156d691fe5> in <module>()
----> 1 import tensorflow as tf

C:ProgramDataAnaconda3libsite-packagestensorflow__init__.py in <module>()
     22 
     23 # pylint: disable=g-bad-import-order
---> 24 from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
     25 # pylint: disable=wildcard-import
     26 from tensorflow.tools.api.generator.api import *  # pylint: disable=redefined-builtin

C:ProgramDataAnaconda3libsite-packagestensorflowpython__init__.py in <module>()
     47 import numpy as np
     48 
---> 49 from tensorflow.python import pywrap_tensorflow
     50 
     51 # Protocol buffers

C:ProgramDataAnaconda3libsite-packagestensorflowpythonpywrap_tensorflow.py in <module>()
     72 for some common reasons and solutions.  Include the entire stack trace
     73 above this error message when asking for help.""" % traceback.format_exc()
---> 74   raise ImportError(msg)
     75 
     76 # pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long

ImportError: Traceback (most recent call last):
  File "C:ProgramDataAnaconda3libsite-packagestensorflowpythonpywrap_tensorflow_internal.py", line 14, in swig_import_helper
    return importlib.import_module(mname)
  File "C:ProgramDataAnaconda3libimportlib__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 571, in module_from_spec
  File "<frozen importlib._bootstrap_external>", line 922, in create_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:ProgramDataAnaconda3libsite-packagestensorflowpythonpywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:ProgramDataAnaconda3libsite-packagestensorflowpythonpywrap_tensorflow_internal.py", line 17, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:ProgramDataAnaconda3libsite-packagestensorflowpythonpywrap_tensorflow_internal.py", line 16, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow_internal')
  File "C:ProgramDataAnaconda3libimportlib__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'


Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

I’ve recently gone through the installation of tensorflow (and struggled a little) and when I believed I had got it, I now get these import errors when running a file that ONLY contains import tensorflow as tf, I ran the cmd: python3 tftest.py and get these import errors:

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
  File "/usr/lib/python3.4/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
ImportError: /usr/local/lib/python3.4/dist-packages/tensorflow/python/_pywrap_tensorflow.so: invalid ELF header

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "stockprice.py", line 1, in <module>
    import tensorflow as tf
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/__init__.py", line 60, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
  File "/usr/lib/python3.4/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
ImportError: /usr/local/lib/python3.4/dist-packages/tensorflow/python/_pywrap_tensorflow.so: invalid ELF header


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.

I do have tensorflow installed

Name: tensorflow
Version: 0.12.0
Location: /usr/local/lib/python3.4/dist-packages
Requires: numpy, six, protobuf, wheel

I’ve been trying to figure this out for hours, has anyone encountered this or a similar error? I’ve looked at installation manuals, and followed every single step I could. I’ve tried reintalling protobuf

I am not running my test file on the tensorflow directory.

I would really REALLY appreciate any help since this error is draining my brain out.

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.

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 is a framework that is commonly used for deep learning and the building of applications that involve multi-layered neural networks. It is worth mentioning that this framework is significantly gaining increasing acceptance all over the world. Partly because it is easy to use and deploy and partly because it can work with the various programming language. It is generally for these reasons and many others, that the Tensorflow library is mostly acclaimed to make machine learning a lot less complicated. Helping developers create wonderful applications that run on multiple APIs very easily. Companies such as Google (obviously because they created the framework), Coca-Cola, Airbnb, and Twitter are a few of those taking full advantage of Tensorflow.i

However, working with Tensorflow is never completely without its unique problems as a single Tensorflow mean square error can have a devastating effect on even the finest piece of work.

What are Tensorflow Errors and Types of Errors

Tensorflow is preferred amongst developers because it usually takes very large datasets, then learns and relearns them over and over again to increase efficiency. And this type of large scale training and retraining is a big deal in both deep learning and machine learning. The model works through a very straightforward process; a structure known as dataflow is first created, then the dataset is moved through one processing node (also known as a graph) to the next and then the next one. And in between each node is a multidimensional data known as tensor.

When anything goes wrong during the process described above, the code would return a Tensorflow error. Practically speaking, some of these errors may occur during the time an application or program is being created. While in other cases the issues may only be returned during the deployment and execution of these programs and application built on deep neural networks that contain the Tensorflow mean square error.

Usually, it is only the mathematical operations of the Tensorflow framework that is built on another complex language such as C++. The largest part of a Tensorflow framework is written and built on Python. For this reason, many of the common errors observed with the framework are those that are common with Python codes.

The two most common types of Tensorflow errors are AttributeError and ImportError.

  • Class AttributeError

Whenever we are working with Tensorflow and we try to give an incorrect assignment or a wrong reference, the program would return what we call AttributeError. The error usually occurs when we try to append integer objects as integer objects do not support appending as a matter of principle.

Inspect the piece of codes below:

Running it will give us the output below:

  • Class ImportError

This is one of Tensorflow common installation problems. The error is returned when we install a wrong version of Tensorflow and then try to call a module that is not supported by the installed version.

A Tensorflow import error is recognized as the base for what developers call the ModuleNotFoundError. When the import statement cannot load a requested module (because it doesn’t exist on the installed version) or when the line of code from…import cannot find a name that has been requested, the result is an error importing Tensorflow.

Let’s say we try to run the line of code below:

What we will get as output would be the Tensorflow import error below:

The errors above are considered as the most frustrating of Tensorflow common installation problems. However, they are not the only common errors that may be raised while using Tensorflow. Other common errors include:

  • Class AssertionError

Bugs are a common occurrence when trying to train a model and they occur in Tensorflow as well. When developers are trying to debug a piece of code to test conditions, they use assert statements. An AssertionError, therefore, occurs when the assert statement being used fails.

Let’s say we try to run the code with assert statement below:

There is no way the objects (a and b) are equal to each other. Hence output would be the AssertionError below:

  • Class MemoryError

This error is common because with Tensorflow we are allowed the chance to work with very large datasets. And while working with these datasets to train a program the objects and variables that we write are usually stored on the RAM of our computers. This is not always a problem until the data file we are working with becomes too large for the RAM to handle. It is usually at that point that a MemoryError will be returned and our program would seize to run.

  • Class DataLossError

Developers have also identified Tensorflow losses to be a very common occurrence when working with this framework. A tf.losses.mean_squared_error can occur when data is truncated in the middle of a training exercise. The truncation usually occurs because the data being used has been lost irrecoverably or there has been some form of corruption on the data file.

How to Deal with Mean Square Error Tensorflow

Dealing with Tensorflow mean errors is an important part of the job of any developer. And since the errors are common and mostly similar, we can easily deal with this error by reading what other Tensorflow users did when they too experienced such errors. Some of the best ways to deal with these errors include, but are not limited to the following:

  • Run Multiple Training Cycles

Detecting a Tensorflow mean squared error is the first step towards rectifying it. And the best way to identify an error is to run the training iterations several times. When you run the program repeatedly for an appropriate number of times and it does not return any failures or errors, you can then go ahead to build and deploy the application. However, if it returns an error message after some iterations, you use one of the other many ways to deal with the issue.

  • Using the ‘Try’, ‘Except’, ‘Else’, and ‘Finally’ Blocks

Using these blocks in that particular order helps us detect where an error can be thrown and even go ahead to run the code despite the error at the end of the ‘finally’ block.

  • Using the Right Parameters

As using the wrong parameters such as shape can sometimes result in a Tensorflow squared mean error, it is always good to check to see that we are using the right parameters. Tensorflow framework is unique and some parameters are simply specific to it. It is good that we remember this as we may be confronted with strange issues that may not occur in other traditional computations.

  • Using the Right Commands on the Right Version

An error can be thrown when we use an old command on a newer version of Tensorflow when the newer version does not contain such commands in its libraries. And in some cases, the commands and arguments could exist in the library of the newer Tensorflow but in a different arrangement. Using the right commands with the right version of Tensorflow or simply changing the arrangements of the argument could help deal with errors.

  • Using the APIs Properly

Even though Tensorflow can be used across a rich set of APIs, different APIs use different assumptions. A training with the same dataset may, therefore, be successful on one API and then fail on another API. Understanding the assumptions that the API you are working with will significantly help deal with failures and errors.

Examples of Common Tensorflow Mean Errors

The following are examples of Tensorflow errors that we have collated from various Tensorflow users.

  1. The first example is a  mean squared error example with a loss function. Generally, developers use the loss function for predictions during a Tensorflow training.

loss = tf.reduce_sum(tf.pow(prediction – Y,2))/(n_inoss = tf.reduce_mean(tf.squared_difference(prediction, Y))

loss = tf.nn.l2_loss(prediction – Y)

tf.squared_difference is the same as tf.pow. Hence, the first two lines of the above code would yield the same result. The third line will, however, return the result of ½ of the squared Euclidean number.

  1. The second example is a piece of code that results in an AttributeError.
>>> import tensorflow as tf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "/Library/Python/2.7/site-packages/tensorflow/python/__init__.py", line 47, in <module>
    import numpy as np
  File "/Library/Python/2.7/site-packages/numpy/__init__.py", line 142, in <module>
    from . import core
  File "/Library/Python/2.7/site-packages/numpy/core/__init__.py", line 57, in <module>
    from . import numerictypes as nt
  File "/Library/Python/2.7/site-packages/numpy/core/numerictypes.py", line 111, in <module>
    from ._type_aliases import (
  File "/Library/Python/2.7/site-packages/numpy/core/_type_aliases.py", line 63, in <module>
    _concrete_types = {v.type for k, v in _concrete_typeinfo.items()}
  File "/Library/Python/2.7/site-packages/numpy/core/_type_aliases.py", line 63, in <setcomp>
    _concrete_types = {v.type for k, v in _concrete_typeinfo.items()}
AttributeError: 'tuple' object has no attribute 'type'

The last example is one that results in an ImportError:

>>> import tensorflow 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "/Library/Python/2.7/site-packages/tensorflow/python/__init__.py", line 47, in <module>
    import numpy as np
  File "/Library/Python/2.7/site-packages/numpy/__init__.py", line 140, in <module>
    from. import _distributor_init
ImportError: cannot import name _distributor_init

Solutions and Tips for Handling Common Tensorflow Mean Square Errors

Below are some of our favorite solutions and tips for handling the common Tensorflow mean square errors:

  • Always upgrade to the latest version of both Tensorflow and Python
  • Be sure you are using a 64bit computer as Tensorflow only works on that
  • Be sure you have enough space on your computer
  • Have a good understanding of the commands and arguments that work on your version of Tensorflow
  • Understand the different assumptions associated with the APIs you use

Conclusion

A Tensorflow mean square error may sound like a very simple concept yet it can have a devastating effect on our works as developers. This is wof we have not only highlighted the problems but some of the common solutions as well. When it happens that we import Tensorflow as tf error, we can try one of the many ways of handling the error and then try to resolve it. The same thing applies when we experience an error while trying to install Tensorflow.

We aim to provide as much knowledge on machine learning as possible and subscribing
to our newsletter will help keep you up to date. We have also created a comprehensive course on Tensorflow. Would you like to check it out?

There are several ways to install TensorFlow on Ubuntu. The easiest way is to install via pip. Unfortunately, this easy installation may result in a bumpy first time experience of running TensorFlow. Consider the following one line Python script:

$ python -c 'import tensorflow as tf;'

This should be where the excitement begins, the moment where conviction about the new era of AI-powered banalities starts to bloom. Yet, the reality can be unexpectedly different. Executing the command may immediately raise this very infamous error:

Illegal instruction (core dumped)

This means that TensorFlow has crashed even before it does anything. What a surprise!

The good thing is that we can run gdb to debug Python and start analyzing the call stack. But what’s even better is that we can save the brilliance for later. This error has been repeatedly reported and has conveniently sat on its fame for a while, as reflected on the issue page.

In brief, the error will be thrown if we’re running recent TensorFlow binaries on CPU(s) that do not support Advanced Vector Extensions (AVX), an instruction set that enables faster computation especially for vector operations. Starting from TensorFlow 1.6, pre-built TensorFlow binaries use AVX instructions. An excerpt from TensorFlow 1.6 release announcement:

...
Breaking Changes
Prebuilt binaries are now built against CUDA 9.0 and cuDNN 7.
Prebuilt binaries will use AVX instructions. This may break TF on older CPUs.
...

This implicitly means that the latest version, which is TensorFlow 1.10 by the time this article is written, also use AVX instructions. Hence, the crash on older CPUs.

Verifying AVX Support

Assumption can mislead and should be proven with validation. Despite presuming that the crash might be caused by the absence of AVX support in the CPU, we may need to verify this. We do so by obtaining the information about CPU features and filtering to the features to find out about AVX availability. We use the following command to list all the CPU features.

$ more /proc/cpuinfo | grep flags

Compare these two sample outputs, the first is from a machine with old CPU and the latter is from another machine with more modern CPU.

Older CPU:


...
flags   : fpu de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pse36 clflush mmx fxsr sse sse2 syscall nx lm rep_good nopl pni cx16 hypervisor lahf_lm
...

Newer CPU:


...
flags   : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb invpcid_single retpoline kaiser tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm xsaveopt cqm_llc cqm_occup_llc dtherm ida arat pln pts
...

As you can immediately observe, the newer CPU is shipped with many more features, including AVX and AVX2 instruction sets. This is a stark contrast compared to the older CPU, which provides more limited features, hence less performance optimization opportunity.

So, what is the resolve if the CPU in your current machine does not support AVX? We have two possible options:
1. Downgrading to TensorFlow 1.5, which does not use AVX instruction in the binaries
2. Compile TensorFlow and install with only possible CPU optimization

Downgrading to TensorFlow 1.5

The downgrade process is very simple as outlined below.

Step 1: Uninstall the currently installed TensorFlow module

$ pip uninstall tensorflow

Step 2: Install TensorFlow 1.5

$ pip install tensorflow==1.5

Step 3: Verify that the error disappears when running TensorFlow

$ python -c 'import tensorflow as tf; print(tf.__version__)'

After completing the downgrade, we will now be able to run TensorFlow code for serving a model. However, we are running somewhat older version of TensorFlow and may suffer from other bugs or issues that have not been resolved for that version. If running the latest TensorFlow is a preferred route, you can take a look at the explanation in the next section

Installing TensorFlow from Source (Custom Build)

The TensorFlow official documentation provides the guide for building TensorFlow from source. However, the documentation did not really specify how to optimize the source build especially for TensorFlow with CPU support-only. Build optimization takes place by appending additional flags to -march=native, which is the default optimization flag. Optimization flags vary from one machine to another.

To find possible optimization flags in the current machine, we run this command on the command line prompt:

$ grep flags -m1 /proc/cpuinfo | cut -d ":" -f 2 | tr '[:upper:]' '[:lower:]' | { read FLAGS; OPT="-march=native"; for flag in $FLAGS; do case "$flag" in "sse4_1" | "sse4_2" | "ssse3" | "fma" | "cx16" | "popcnt" | "avx" | "avx2") OPT+=" -m$flag";; esac; done; MODOPT=${OPT//_/.}; echo "$MODOPT"; }

From the previous two CPU samples, we will have “-march=native -mcx16” flags for the older CPU and “-march=native -mssse3 -mfma -mcx16 -msse4_1 -msse4_2 -mpopcnt -mavx -mavx2” flags for the more modern CPU. We supply these flags to the build configurator and then generate the WHL file that can be installed to the system.

The full instruction for building TensorFlow that targets CPU optimization is explained in this article.

Github Repository TensorFlow CPU Custom Build

For some reasons, you may find it less practical to build from source and will prefer a more convenient way to install the custom TensorFlow CPU build. If you want to go this route, you can check this Github repository that hosts TensorFlow custom builds, starting from TensorFlow 1.10. Custom builds for future releases will also be added to this repository, subject to the availability of machines and other resources to perform the source build.

TensorFlow я устанавливал таким образом:

C:> pip install --upgrade tensorflow // cpu
C:> pip install --upgrade tensorflow-gpu // gpu

Импортировал так:

import tensorflow as ts

Ошибка:

Traceback (most recent call last):
  File "C:ProgramDataMiniconda3libsite-packagestensorflowpythonpywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:ProgramDataMiniconda3libsite-packagestensorflowpythonpywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:ProgramDataMiniconda3libsite-packagestensorflowpythonpywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:ProgramDataMiniconda3libimp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "C:ProgramDataMiniconda3libimp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: DLL load failed with error code -1073741795

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File ".parsersunitest_test-weather.py", line 22, in <module>
    import tensorflow as tf
  File "C:ProgramDataMiniconda3libsite-packagestensorflow__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:ProgramDataMiniconda3libsite-packagestensorflowpython__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:ProgramDataMiniconda3libsite-packagestensorflowpythonpywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:ProgramDataMiniconda3libsite-packagestensorflowpythonpywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:ProgramDataMiniconda3libsite-packagestensorflowpythonpywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:ProgramDataMiniconda3libsite-packagestensorflowpythonpywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:ProgramDataMiniconda3libimp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "C:ProgramDataMiniconda3libimp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: DLL load failed with error code -1073741795


Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Понравилась статья? Поделить с друзьями:
  • Import system python ошибка
  • Import sqlalchemy error
  • Import seaborn as sns ошибка
  • Import requests python 3 ошибка
  • Import requests error