ImportError: cannot import name 'keras'

Question:

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?

Asked By: Ronan Venkat

||

Answers:

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

! pip install tensorflow --upgrade
Answered By: Omer Tekbiyik

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()
Answered By: desertnaut

I was also 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:Usersveni_anaconda3Libsite-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"

PS: This is my first answer, if I missed anything or overdid. Please forgive.

Your fellow coder!!

Answered By: Ashu Singh
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.