WillGFR
WillGFR

Reputation: 75

Import tensorflow issue on Python 3.6

When I try to import tensorflow in my Python scripts, I have some weird results. For instance:

import tensorflow 
from keras.datasets import imdb

gives me

ModuleNotFoundError
Traceback (most recent call last) <ipython-input-12-25cf0f878919> in <module>()
      1 import tensorflow
----> 2 from keras.datasets import imdb

ModuleNotFoundError: No module named 'keras'

If I try:

import tensorflow as tf
from tf.keras.datasets import imdb

I get :

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-9-bd3db3d3567b> in <module>()
      1 import tensorflow as tf
----> 2 from tf.keras.datasets import imdb

ModuleNotFoundError: No module named 'tf'

But, if I use :

from tensorflow.keras.datasets import imdb

it works.

I've been googling this for a full hour now, and I still don't understand what I'm doing wrong in the first two scripts. Thanks

Upvotes: 1

Views: 2923

Answers (1)

Leo K
Leo K

Reputation: 5354

You haven't specified how and where you installed tensorflow, so I could be wrong, but:

(a) it appears that keras is installed with tensorflow, but not in a location that is in the default Python path (hence, you cannot do from keras.datasets import imdb).

(b) this combination:

import tensorflow as tf
from tf.keras.datasets import imdb

is invalid, because from x import y searches for x as a module and not as a symbol in your code's globals (and tf is NOT a module name but a global variable, import tensorflow as tf imports tensorflow and sets tf to point to the module object).

Therefore (unless you fix your install or your PYTHONPATH to make keras visible as a module), you should use this to import keras (or specific symbols from it):

# either this, to access keras.*, e.g., keras.datasets.imdb
import tensorflow.keras as keras

# or this, as you've done in your example
from tensorflow.keras.datasets import imdb

Upvotes: 3

Related Questions