tensorflow: ModuleNotFoundError: No module named 'tensorflow_core.keras' in Flask

Please make sure that this is a build/installation issue. As per our GitHub Policy, we only address code/doc bugs, performance issues, feature requests and build/installation issues on GitHub. tag:build_template

System information

  • OS X 10.15.1 Catalina
  • TensorFlow version: 1.15.0
  • Python version: 3.7.3
  • virtualenv (Flask)

Describe the problem I’m unable to import and run a model using Flask services because of this error: ModuleNotFoundError: No module named ‘tensorflow_core.keras’

Provide the exact sequence of commands / steps that you executed before running into the problem

  • I have pip installed keras and tensorflow into my virtualenv (I’ve also tried pip3 install)
  • My code is like this:
import tensorflow as tf
from keras.models import load_model
model = load_model("model.hdf5")
# ... preprocess images
predictions = model.predict(processed_images)

Any other info / logs Include any logs or source code that would be helpful to diagnose the problem. If including tracebacks, please include the full traceback. Large logs and files should be attached.

Traceback (most recent call last):
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/bin/flask", line 8, in <module>
    sys.exit(main())
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/flask/cli.py", line 966, in main
    cli.main(prog_name="python -m flask" if as_module else None)
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/flask/cli.py", line 586, in main
    return super(FlaskGroup, self).main(*args, **kwargs)
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/click/core.py", line 1137, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/click/decorators.py", line 64, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/flask/cli.py", line 860, in run_command
    extra_files=extra_files,
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/werkzeug/serving.py", line 1008, in run_simple
    run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/werkzeug/_reloader.py", line 337, in run_with_reloader
    reloader.run()
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/werkzeug/_reloader.py", line 202, in run
    for filename in chain(_iter_module_files(), self.extra_files):
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/werkzeug/_reloader.py", line 24, in _iter_module_files
    filename = getattr(module, "__file__", None)
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/tensorflow/__init__.py", line 50, in __getattr__
    module = self._load()
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/tensorflow/__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "/Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.keras'
Using TensorFlow backend.
Using TensorFlow backend.
WARNING:tensorflow:From /Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
WARNING:tensorflow:From /Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
WARNING:tensorflow:From /Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:4070: The name tf.nn.max_pool is deprecated. Please use tf.nn.max_pool2d instead.

WARNING:tensorflow:From /Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:4070: The name tf.nn.max_pool is deprecated. Please use tf.nn.max_pool2d instead.

2019-11-26 15:33:29.703531: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7fb84403e4f0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2019-11-26 15:33:29.703585: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
2019-11-26 15:33:29.705059: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7fa1f9bbcd00 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2019-11-26 15:33:29.705389: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
WARNING:tensorflow:From /Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
WARNING:tensorflow:From /Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
WARNING:tensorflow:From /Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:422: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.

WARNING:tensorflow:From /Users/llemonthyme/Desktop/traffic-app/flaskservice/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:422: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 21
  • Comments: 68 (2 by maintainers)

Most upvoted comments

I’ve been struggling with this issue for the past few days, I just tried to run flask with debug mode off and the exception no longer occurs. As an annoying work around setting FLASK_DEBUG=1 allows you to continue working but you’ll need to restart your server after every change.

I’m still trying to figure out why flask debug mode is causing this issue.

It looks like passing --eager-loading to the flask run command is another work around.

I’m getting the same issue. Simply adding the line “from tensorflow import keras” into my flask app.py will cause the error: ModuleNotFoundError: No module named 'tensorflow_core.keras'

this seems to have worked

from tensorflow import keras
model = keras.models.load_model(new_model)

vs failing

from keras.models import load_model
model = load_model(new_model)

UPDATE: for those using Flask, TF2, and gunicorn

For those running flask through gunicorn, I found that running

gunicorn -b 0.0.0.0:5000 -w 4
        --access-logfile -
        --reload
        app:app

was causing issues with the --reload flag. So basically you would get the ModuleNotFoundError: No module named 'tensorflow_core.keras' error. But if you removed the --reload flag it would fix the error. However, while developing your app, you want to be able to use --reload. I was using gunicorn = “==19.9.0”.

But, when I upgraded to gunicorn = "==20.0.4" everything was fixed. Here are some of the package versions I was using.

Flask==1.1.1
Flask-CeleryExt==0.3.4
Flask-Cors==3.0.8
Flask-SQLAlchemy==2.4.1
gunicorn==20.0.4
numpy==1.18.1
Pillow==7.0.0
protobuf==3.11.3
scikit-learn==0.22.1
scipy==1.4.1
tensorboard==2.1.0
tensorflow==2.1.0
tensorflow-estimator==2.1.0

As other comments have mentioned, a similar error happens in Django as well. I am facing the same issue with:

Python 3.6.1
Django 2.0.3

Thanks to other comments I have found it only happens with tensorflow==1.15.0 and tensorflow==2.0 Hence, a possible workaround is to downgrade to tensorflow==1.14.0 or below.

Another workaround I have found, which is ugly as well, is to include

import tensorflow as tf

in the import section of the app’s manage.py

I hope that information could also help to eventually resolve the bug.

same here with Flask==1.1.1 tensorflow==1.15.0 in a ubuntu 18.04 docker. I have to set FLASK_DEBUG=0 to let it work.

I stopped getting ModuleNotFoundError: No module named ‘tensorflow_core.keras’ in Flask when I used

export FLASK_APP=your_app_name

flask run

i.e didn’t use export FLASK_ENV=development

Flask==1.1.1 pdfminer.six==20200124 lmdb==0.98 flask-cors==3.0.8 numpy==1.17.4 tensorflow==2.1.0 keras nltk

environment:

  • FLASK_DEBUG=0
  • FLASK_APP_CONFIG=Product

did the trick for me.

The recommended way to prevent this is to:

  1. install using python -m pip install ...
  2. check using python -m pip list

Or, to use virtualenvs or similar.

I’ve got the same error, but with django though. Python 3.7.5 TF 1.15.0. With TF 1.14.0 it works fine.

Using TensorFlow backend.
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 61, in execute
    super(Command, self).execute(*args, **options)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 100, in handle
    self.run(**options)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in run
    autoreload.main(self.inner_run, None, options)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 341, in main
    reloader(wrapped_main_func, args, kwargs)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 307, in python_reloader
    reloader_thread()
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 277, in reloader_thread
    change = fn()
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 206, in code_changed
    for filename in gen_filenames():
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 104, in gen_filenames
    [filename.__file__ for filename in new_modules
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 105, in <listcomp>
    if hasattr(filename, '__file__')])
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/tensorflow/__init__.py", line 50, in __getattr__
    module = self._load()
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/tensorflow/__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.keras'

Which is super strange, because when I call the import directly from a python interpreter in terminal - it works:

from tensorflow import keras

Even loading a model works.

Same issue here. Just FLASK_DEBUG=0 helps

I am facing the same issue when running my flask app in a docker container.

Hello everyone, Even I was getting the same error in a flask application. I did the following and it worked, pip uninstall tensorflow pip install tensorflow==2.0.

Does not work. I tried this and still getting same error.

Thank you for the reproduction.

It seems this is going to be solved in 2.2, but it happens in 1.15 and 2.1. Unfortunately, I’m not sure if we can backport a fix safely.

(env) [tf] λ pip install -q tensorflow-cpu==2.2.0rc2
(env) [tf] λ python test.py 
(env) [tf] λ pip uninstall -y tensorflow-cpu
Found existing installation: tensorflow-cpu 2.2.0rc2
Uninstalling tensorflow-cpu-2.2.0rc2:
  Successfully uninstalled tensorflow-cpu-2.2.0rc2
(env) [tf] λ pip install -q tensorflow-cpu==2.1
(env) [tf] λ python test.py 
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    getattr(module, "__file__", None)
  File "/tmp/tf/env/lib64/python3.7/site-packages/tensorflow/__init__.py", line 50, in __getattr__
    module = self._load()
  File "/tmp/tf/env/lib64/python3.7/site-packages/tensorflow/__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.keras'
(env) [tf] λ pip uninstall -y tensorflow-cpu
Found existing installation: tensorflow-cpu 2.1.0
Uninstalling tensorflow-cpu-2.1.0:
  Successfully uninstalled tensorflow-cpu-2.1.0
(env) [tf] λ pip install -q tensorflow-cpu==1.15
(env) [tf] λ python test.py 
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    getattr(module, "__file__", None)
  File "/tmp/tf/env/lib64/python3.7/site-packages/tensorflow/__init__.py", line 50, in __getattr__
    module = self._load()
  File "/tmp/tf/env/lib64/python3.7/site-packages/tensorflow/__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.keras'

(where test.py is the code in the reproducer)

pip uninstall tensorflow after that pip install tensorflow worked for me

I’m also running into this issue with the flask run command in development with the latest versions of tensorflow and flask: FLASK_ENV=development flask run

Has anybody gleaned any insight into the problem?

It seems that enough people are taxed by it to warrant an economic incentive for its fix. Any interest in pooling together to establish a reasonable bug bounty?

I have the same error with Python 3.7.5, TensorFlow 2.0.0, Flask 1.1.1 on macOS 10.14.6.

Unfortunately, the error does not occur every time. Sometimes it will take up to 100 reload/req cycles to cause the exception:

i=0 ; while true ; do i=$((i+1)); echo ${i}; touch app.py ; sleep 1 ; curl -s -o /dev/null http://localhost:5000 ; done
Traceback (most recent call last):
  File "/Users/testuser/web/v/bin/flask", line 8, in <module>
    sys.exit(main())
  File "/Users/testuser/web/v/lib/python3.7/site-packages/flask/cli.py", line 966, in main
    cli.main(prog_name="python -m flask" if as_module else None)
  File "/Users/testuser/web/v/lib/python3.7/site-packages/flask/cli.py", line 586, in main
    return super(FlaskGroup, self).main(*args, **kwargs)
  File "/Users/testuser/web/v/lib/python3.7/site-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File "/Users/testuser/web/v/lib/python3.7/site-packages/click/core.py", line 1137, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Users/testuser/web/v/lib/python3.7/site-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/testuser/web/v/lib/python3.7/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/Users/testuser/web/v/lib/python3.7/site-packages/click/decorators.py", line 64, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "/Users/testuser/web/v/lib/python3.7/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/Users/testuser/web/v/lib/python3.7/site-packages/flask/cli.py", line 860, in run_command
    extra_files=extra_files,
  File "/Users/testuser/web/v/lib/python3.7/site-packages/werkzeug/serving.py", line 1008, in run_simple
    run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
  File "/Users/testuser/web/v/lib/python3.7/site-packages/werkzeug/_reloader.py", line 337, in run_with_reloader
    reloader.run()
  File "/Users/testuser/web/v/lib/python3.7/site-packages/werkzeug/_reloader.py", line 202, in run
    for filename in chain(_iter_module_files(), self.extra_files):
  File "/Users/testuser/web/v/lib/python3.7/site-packages/werkzeug/_reloader.py", line 24, in _iter_module_files
    filename = getattr(module, "__file__", None)
  File "/Users/testuser/web/v/lib/python3.7/site-packages/tensorflow/__init__.py", line 50, in __getattr__
    module = self._load()
  File "/Users/testuser/web/v/lib/python3.7/site-packages/tensorflow/__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "/Users/testuser/.pyenv/versions/3.7.5/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.keras'

The Werkzeug _reloader is looping over sys.modules.values().

Every keras submodule is in the list. Is it interesting that tensorflow_core.keras occasionally appears twice? It is the only one duplicated in the occurrence below.

import sys
k = [ str(m) for m in list(sys.modules.values()) if 'tensorflow_core.keras' in str(m) ]
len(k) # => 47
k[0:3]
[<module 'tensorflow_core.keras' from '/tmp/app/v/lib/python3.7/site-packages/tensorflow_core/python/keras/api/_v2/keras/__init__.py'>,
 <module 'tensorflow_core.keras' from '/tmp/app/v/lib/python3.7/site-packages/tensorflow_core/python/keras/api/_v2/keras/__init__.py'>,
 <module 'tensorflow_core.keras.activations' from '/tmp/app/v/lib/python3.7/site-packages/tensorflow_core/python/keras/api/_v2/keras/activations/__init__.py'>]

Also, without list(), the above code warns the sys.modules dictionary has changed during iteration. Werkzeug knows about this and uses list() as well.

I am not using Django, but it was mentioned up-thread, so I briefly skimmed its reloader. It similarly watches all modules by looping over sys.modules keys.

I’m not sure if this is a “bug” in Tensorflow, or a consequence of how other code is reloading modules. I know very little about the Python module system.

Closing this issue as it is solved in 2.2

I’ve got the same error, but with django though. Python 3.7.5 TF 1.15.0. With TF 1.14.0 it works fine.

Using TensorFlow backend.
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 61, in execute
    super(Command, self).execute(*args, **options)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 100, in handle
    self.run(**options)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in run
    autoreload.main(self.inner_run, None, options)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 341, in main
    reloader(wrapped_main_func, args, kwargs)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 307, in python_reloader
    reloader_thread()
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 277, in reloader_thread
    change = fn()
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 206, in code_changed
    for filename in gen_filenames():
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 104, in gen_filenames
    [filename.__file__ for filename in new_modules
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/django/utils/autoreload.py", line 105, in <listcomp>
    if hasattr(filename, '__file__')])
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/tensorflow/__init__.py", line 50, in __getattr__
    module = self._load()
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/site-packages/tensorflow/__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "/opt/anaconda2/envs/ocr_ws_dev/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.keras'

Which is super strange, because when I call the import directly from a python interpreter in terminal - it works:

from tensorflow import keras

Even loading a model works.

I has a similar problem while integrating keras model to django framework. Using TensorFlow backend.

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\core\management\__init__.py", line 381, in execute
_from_command_line
    utility.execute()
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\core\management\__init__.py", line 375, in execute

    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\core\management\base.py", line 316, in run_from_ar
gv
    self.execute(*args, **cmd_options)
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\core\management\commands\runserver.py", line 60, i
n execute
    super().execute(*args, **options)
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\core\management\base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\core\management\commands\runserver.py", line 95, i
n handle
    self.run(**options)
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\core\management\commands\runserver.py", line 102,
in run
    autoreload.main(self.inner_run, None, options)
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\utils\autoreload.py", line 323, in main
    python_reloader(wrapped_main_func, args, kwargs)
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\utils\autoreload.py", line 302, in python_reloader

    reloader_thread()
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\utils\autoreload.py", line 274, in reloader_thread

    change = fn()
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\utils\autoreload.py", line 203, in code_changed
    for filename in gen_filenames():
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\utils\autoreload.py", line 101, in gen_filenames
    [filename.__file__ for filename in new_modules
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\django\utils\autoreload.py", line 102, in <listcomp>
    if hasattr(filename, '__file__')])
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\tensorflow\__init__.py", line 50, in __getattr__
    module = self._load()
  File "C:\Users\pc\Anaconda3\envs\kr\lib\site-packages\tensorflow\__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "C:\Users\pc\Anaconda3\envs\kr\lib\importlib\__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 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.keras'

But I don’t know how to fix it. Longing for your reply!

I retrained the model with tensorflow==1.14.0 then saved the model and used gunicorn to run flask. This solved my problem.

I have found that down grading the tensorflow version to 1.x resolved my issue - is everyone experiencing issues using TF 2?

Hi @nikochiko. Thanks for the reply. Unfortunately the solution mentioned in that thread isn’t quite clear:

I was missing CUDA/cudnn on my PATH, adding those then rerunning pip install fixed the issue.

(pip install without CUDA on path does not install: libtensorflow_framework.so.2)

I was unable to find any solution online as to what path was and how to add CUDA/cudnn to it.

@MihailSalnikov Thanks, you’re correct in your reply here

I had old dependencies. Uninstalling everything tf and reinstalling with 2.2.0rc3 fixed my problem. Thank you

It works! Thanks a lot!

| | 叶田地 | | 邮箱:18365225454@163.com |

签名由 网易邮箱大师 定制

On 04/22/2020 00:43, Mihai Maruseac wrote:

@TDYe123 solution was mentioned 1 and 2 comments above yours. Either downgrade to 1.14 (not recommended) or upgrade to 2.2 release candidate (final to be released soon)

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or unsubscribe.

@TDYe123 solution was mentioned 1 and 2 comments above yours. Either downgrade to 1.14 (not recommended) or upgrade to 2.2 release candidate (final to be released soon)

Recommend upgrading to 2.2 where this issue is also fixed (rc3 is available for testing now, final release will be early next week). This is because 1.14 release has a large number of bugs and inconsistencies and is already outside the support window. Sure, switching to 2.2 means upgrading to use TF2.0 APIs but this is also something we recommend.

Here’s a minimal, reproducible example of this error that only imports tensorflow. EDIT: made even smaller

import sys
from threading import Thread
import time

def loader():
    import tensorflow

t = Thread(target=loader, args=())
t.start()

while True:
    for module in list(sys.modules.values()):
        getattr(module, "__file__", None)
    time.sleep(1)

@mihaimaruseac I’ve seen several people mention that it also affects the Django reloader. I’m wondering if there’s a way to modify TensorFlow so that both the Flask and Django reloaders will work with it.

UPDATE: for those using Flask, TF2, and gunicorn

For those running flask through gunicorn, I found that running

gunicorn -b 0.0.0.0:5000 -w 4
        --access-logfile -
        --reload
        app:app

was causing issues with the --reload flag. So basically you would get the ModuleNotFoundError: No module named 'tensorflow_core.keras' error. But if you removed the --reload flag it would fix the error. However, while developing your app, you want to be able to use --reload. I was using gunicorn = “==19.9.0”.

But, when I upgraded to gunicorn = "==20.0.4" everything was fixed. Here are some of the package versions I was using.

Flask==1.1.1
Flask-CeleryExt==0.3.4
Flask-Cors==3.0.8
Flask-SQLAlchemy==2.4.1
gunicorn==20.0.4
numpy==1.18.1
Pillow==7.0.0
protobuf==3.11.3
scikit-learn==0.22.1
scipy==1.4.1
tensorboard==2.1.0
tensorflow==2.1.0
tensorflow-estimator==2.1.0

Same here! Also giving more ram to Docker made my flask app start, otherwise the workers would just restart indefinitely

I’m also facing the same issue when using TensorFlow v2.1.0 and 2.0.0 with Flask in Docker & Docker-Compose. As mentioned in above threads, setting FLASK_DEBUG=0 worked for my case.

Another way that worked for my case and allows keeping FLASK_DEBUG=1 during development is to use package versions Flask==1.1.1 and tensorflow==2.0.0-beta1. By the way, I’m using this flask+docker image from uwsgi-nginx-flask-docker

Thanks @enriqueav I worked I was facing this same error with:

python 3.6.4 Django 1.11 Tensorflow 2

Apparently as you said when placing the import:

import tensorflow as tf

In the apps section manage.py The django server runs without any problem.

@alexespencer I’m experiencing the issue in TF2, What 1.x version worked for you? I tried 1.15 and 1.14 but still had the error.

Sorry for the delay. I had to roll back to Tensorflow 1.13.1 to get this to work.