9

When running this in Jupyter notebooks (python):

import tensorflow as tf
from tensorflow import keras

I get this error:

ImportError: cannot import name 'keras'

I've tried other commands in place of the second one, such as (but not limited to)

from tensorflow.keras import layers

But it always returns some error. I'm using the online version of Jupyter, and running print(tf.VERSION) returns 1.1.0. I'm not sure if the problem is just that I have the wrong version, or if it's something else. How do I fix this?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Ronan Venkat
  • 345
  • 1
  • 6
  • 12

3 Answers3

8

I think you are using old version tensorflow Try to update it like

! pip install tensorflow --upgrade
Omer Tekbiyik
  • 4,255
  • 1
  • 15
  • 27
4

You have an old version of Tensorflow; to access Keras from Tensorflow 1.1, you should use

import tensorflow.contrib.keras as keras

For Sequential, use

from tensorflow.contrib.keras.python.keras.models import Sequential
model = Sequential()
desertnaut
  • 57,590
  • 26
  • 140
  • 166
  • Where would I get that message? I just imported it in JupyterLabs and it didn’t return an error, but then I tried: model = keras.Sequential() and it returned an error. – Ronan Venkat Feb 24 '19 at 00:08
  • what about for other modules, like Flatten and Dense? Would I just import the respective module and replace Sequential with Flatten or Dense? And is there a way to do it without so many import lines? – Ronan Venkat Feb 24 '19 at 00:43
  • @RonanVenkat for layers,you replace `models` with `layers`. And no, with the version of Tensorflow you are using you cannot avoid the long imports... – desertnaut Feb 24 '19 at 00:45
  • I get an error that says `ModuleNotFoundError: No module named 'tensorflow.contrib'` when I try this. – user3367130 Aug 27 '20 at 00:17
  • @user3367130 pls open a new question with the details – desertnaut Aug 27 '20 at 09:10
0

I also was not able to import keras from tensorflow. I was getting the following error:

ImportError: cannot import name 'keras' from 'tensorflow' (unknown location)

After searching for a bit got the solution here:

All that is required is to remove ~(site_package_name) from the directory. In my scenario, it was ~ensorflow and it was somehow blocking the pip to install/upgrade packages. Once I deleted the folder, everything was running smoothly. After deleting the package, install/upgrade the required package.

For those, who are unable to find the directory. Here is mine (just for reference): C:\Users\veni_\anaconda3\Lib\site-packages

Note: The warning itself will show the name of the package that is causing the problem. For e.g.:

 **"WARNING: Ignoring invalid distribution -ensorflow"** 
Blue Robin
  • 847
  • 2
  • 11
  • 31