2
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

Minh1015
  • 21
  • 1
  • 2
  • 1
    New to stackoverflow so if im doing anything wrong just tell me – Minh1015 Sep 01 '20 at 11:59
  • you can try the solution here https://stackoverflow.com/questions/54847380/importerror-cannot-import-name-keras – Mert Karagöz Sep 01 '20 at 12:05
  • It seems to be working now but won't complete the task in https://www.tensorflow.org/guide/keras/sequential_model – Minh1015 Sep 01 '20 at 12:11
  • Does this answer your question? [ImportError: cannot import name 'keras'](https://stackoverflow.com/questions/54847380/importerror-cannot-import-name-keras) – TylerH Sep 04 '20 at 19:13

1 Answers1

1

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.