12
votes

I am trying to run a script, but I struggle already at the imports. This import

from keras.preprocessing.image import save_img

raises the following error:

AttributeError: module 'tensorflow' has no attribute 'name_scope'.

I am using the following packages.

Keras                     2.2.2,                     
Keras-Applications        1.0.4,                   
Keras-Preprocessing       1.0.2,                   
tensorflow                1.9.0,                     
tensorflow-gpu            1.9.0                
7

7 Answers

14
votes

I was unable to reproduce with the same versions of the keras and tensorflow, reinstalling keras and tensorflow, may solve the issue, please use commands below:

pip install --upgrade pip setuptools wheel
pip install -I tensorflow
pip install -I keras

NOTE: The -I parameter stands for ignore installed package.

4
votes

For everyone who use Tensorflow 2.0 and stumble upon this question with the same error, like I did: I solved it by changing the imports from keras.xxx to tensorflow.keras.xxx

1
votes

I also encountered this same problem when I stopped my IDE while executing. Restarting my IDE works for me. Just save your program and restart IDE. Hope it will work for you as well.

0
votes

As Andriy Ivaneyko mentioned above, reinstalling tensorflow helps. I'm not sure why, but installing tensorflow-serving-api breaks something somewhere along the way. We solved this by running:

pip install --force-reinstall tensorflow

Note that this applies to both tensorflow and tensorflow-gpu installations. Specifically, the above command will fix this problem in situations where you're specifically using tensorlfow-gpu. tensorflow-serving-api installs regular tensorflow if it's not already installed.

0
votes

I encountered this same bug and reinstalling tensorflow made no difference, and this caused me some headscratching.

Eventually I noticed that my IDE autocomplete had added the following line to my code:

from tensorflow_core.python.keras.callbacks import EarlyStopping

It seems that directly referencing tensorflow_core.python will break tensorflow.

Replacing this with the normal tensorflow import solved the problem!

from tensorflow.keras.callbacks import EarlyStopping
0
votes

My IDE offered me two different import paths

keras

or

tensorflow_core.python.keras

In my example I could either import like this:

from keras.layers import Dense, Dropout, LSTM, Input, Activation
from keras import optimizers, Model

or like that:

from tensorflow_core.python.keras import Input, Model, optimizers
from tensorflow_core.python.keras.layers import LSTM, Dropout, Dense

Mixing up tensorflow_core.python.keras and plain keras led to the problem in my case. After I imported everything directly from keras and keras.layers, it worked for me.

0
votes

My tensorflow version is 2.1, and I found my tensorflow-estimator version is 2.2

My fix is to downgrade the estimator to the same version