"Cannot import name 'keras'" error when importing keras

Viewed 1591
import tensorflow as tf
from tensorflow import keras

Results are

ImportError                               Traceback (most recent call last)
<ipython-input-1-75a28e3c6620> in <module>
      1 import tensorflow as tf
----> 2 from tensorflow import keras
      3 
      4 import numpy as np
      5 

ImportError: cannot import name 'keras'

Using tensorflow version 1.2.1 and keras version 2.3.1

1 Answers

You are using old version of tensorflow. You can update to latest version using below code

! pip install tensorflow --upgrade

From Tensorflow V2.0 onwards, keras is integrated in tensorflow as tf.keras, so no need to import keras separately.

To create sequential model, you can refer below code

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

#Define Sequential model with 3 layers
model = keras.Sequential(
    [
        layers.Dense(2, activation="relu", name="layer1"),
        layers.Dense(3, activation="relu", name="layer2"),
        layers.Dense(4, name="layer3"),
    ]
)
# Call model on a test input
x = tf.ones((3, 3))
y = model(x)

print("Number of weights after calling the model:", len(model.weights))  # 6

model.summary()

Output:

Number of weights after calling the model: 6
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
layer1 (Dense)               (3, 2)                    8         
_________________________________________________________________
layer2 (Dense)               (3, 3)                    9         
_________________________________________________________________
layer3 (Dense)               (3, 4)                    16        
=================================================================
Total params: 33
Trainable params: 33
Non-trainable params: 0
_________________________________________________________________

For more details please refer Tensorflow Guide. I am happy to help you, if you are not able to complete the task.

Related