Why do we have to import keras from tensorflow if we have already imported tensorflow in python?

Viewed 1171

I'm now learning tensorflow and keras and I see all tutorials have these two imports:

import tensorflow as tf
from tensorflow import keras

Based on my understanding of python import, I thought the second line was an extra, since if we have already imported tensorflow in the first line, then we shall have imported every module in tensorflow. Just like if we have

import math 

then we shouldd have math.log(), math.sqrt() available.

However, if I comment

from tensorflow import keras

then this line of code

model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

would return NameErrorTraceback (most recent call last)

<ipython-input-3-740ba65f0ade> in <module>()
----> 1 model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

NameError: name 'keras' is not defined

Why can't we directly use tf.keras if we only have import tensorflow as tf? What's special about this import compared to the import in import math?

Thanks

2 Answers

When you import a module in python, you import only that module (along with the modules imported by the module), any modules defined in the imported module need to be imported on their own,

example

$ ptree
.
├── imports.py
└── pmod
    ├── cmod.py
    └── __init__.py

1 directory, 3 files

$ cat imports.py 
import pmod

pmod.do()
pmod.cmod.do()

$ python3 imports.py 
hello from pmod
Traceback (most recent call last):
  File "imports.py", line 4, in <module>
    pmod.cmod.do()
AttributeError: module 'pmod' has no attribute 'cmod'

however if I import it explicitly it does work

$ cat imports.py 
import pmod
import pmod.cmod

pmod.do()
pmod.cmod.do()

$ python3 imports.py 
hello from pmod
hello from cmod

The error is not with tf.keras. In your model definition, you use layers from keras and not tf.keras. That's why your'e getting the error when you remove the import. Replace your model definition with:

model = tf.keras.Sequential([tf.keras.layers.Dense(units=1, input_shape=[1])])

Now, you do not need to import keras from tensorflow.

Related