Unable to import keras modules when importing tensorflow with tf alias

  alias, import, module, python, tensorflow

I am facing a weird thing here. I have installed Tensorflow on Ubuntu 20.04 locally.
I have created a virtual environment (I don’t use conda) in vscode.
The tensorflow installation was made with pip as shown on the official Tensorflow site.

(.venv) (base) mundsen1:~/dev/Python/ImageProcessing$ python

Python 3.8.10 (default, Jun  2 2021, 10:49:15) 

[GCC 9.4.0] on linux

Type "help", "copyright", "credits" or "license" for more information.


>>> import tensorflow as tf

2021-09-19 11:32:08.997073: 
tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could 
not load dynamic library 'libcudart.so.11.0'; dlerror: 
libcudart.so.11.0: cannot open shared object file: No such file or 
directory
2021-09-19 11:32:08.997096: I 
tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above 
cudart dlerror if you do not have a GPU set up on your machine.

!!!!!!! THIS WARNING MESSAGE ABOVE IS NOT A PROBLEM SINCE I DO NOT HAVE A GPU.

!!!!!!! What is weird is this:

>>> from tf.keras.models import Model

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'tf'

!!!! WHILE I CAN EXECUTE…

>>> tf.__version__

'2.6.0'

>>> tf.keras.__version__

'2.6.0'


>>> tf.keras.models

<module 'keras.api._v2.keras.models' from /home/alexandre/dev/Python/ImageProcessing/.venv/lib/python3.8/site-packages/keras/api/_v2/keras/models/__init__.py'>


>>> dir(tf.keras.models)

['Model', 'Sequential', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_sys', 'clone_model', 'load_model', 'model_from_config', 'model_from_json', 'model_from_yaml', 'save_model']

>>> for func in dir(tf.keras.models):

...     print(func)

... 

Model

Sequential

__builtins__

__cached__

__doc__

__file__

__loader__

__name__

__package__

__path__

__spec__

_sys

clone_model

load_model

model_from_config

model_from_json

model_from_yaml

save_model

from tensorflow.keras.models import Model, load_model

!!!! NO PROBLEM !

!!!! But When I use tf alias for module imports, it fails…

>>> from tf.keras.models import Model, load_model

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

ModuleNotFoundError: No module named 'tf'

>>> 

So I am able to use tf variable as long as I don’t use it for importing modules.

Does anyone have an idea of what is going here?

It looks to be a pure "Python" issue, I have same problem when executing same instructions in Colab Notebook.

Source: Python Questions

LEAVE A COMMENT