79
import tensorflow as tf
import tensorflow 

from tensorflow import keras
from keras.layers import Dense

I am getting the below error

from keras.layers import Input, Dense
Traceback (most recent call last):

  File "<ipython-input-6-b5da44e251a5>", line 1, in <module>
    from keras.layers import Input, Dense

ModuleNotFoundError: No module named 'keras'

How do I solve this?

Note: I am using Tensorflow version 1.4

Timbus Calin
  • 13,809
  • 5
  • 41
  • 59
GeorgeOfTheRF
  • 8,244
  • 23
  • 57
  • 80

9 Answers9

126

Use the keras module from tensorflow like this:

import tensorflow as tf

Import classes

from tensorflow.python.keras.layers import Input, Dense

or use directly

dense = tf.keras.layers.Dense(...)

EDIT Tensorflow 2

from tensorflow.keras.layers import Input, Dense

and the rest stays the same.

Mihail Burduja
  • 3,196
  • 2
  • 22
  • 28
  • 2
    Any ideas where to find layer_utils? It used to be imported thus: from keras.utils import layer_utils However, following your suggestion above: tensorflow.python.keras.utils import layer_utils results in the error: ImportError: cannot import name 'layer_utils' – Rafael_Espericueta Feb 17 '18 at 00:24
  • 2
    I have the same problem with maxnorm – ARAT Apr 11 '18 at 02:07
  • 3
    The use of tensorflow.python.keras was never ok as it sidestepped the public api. While it worked before TF 2.6, it no longer does because Tensorflow now uses the keras module outside of the tensorflow package. [See Release notes](https://newreleases.io/project/github/tensorflow/tensorflow/release/v2.6.0). ```Keras been split into a separate PIP package (keras), and its code has been moved to the GitHub repository keras-team/keras. The API endpoints for tf.keras stay unchanged, but are now backed by the keras PIP package. ...```. The code is not the same and I had errors mixing them. – A Roebel Jul 27 '22 at 12:26
8

Try from tensorflow.python import keras

with this, you can easily change keras dependent code to tensorflow in one line change.

You can also try from tensorflow.contrib import keras. This works on tensorflow 1.3

Edited: for tensorflow 1.10 and above you can use import tensorflow.keras as keras to get keras in tensorflow.

Ramesh Kamath
  • 189
  • 1
  • 6
  • 3
    i have moved on to [tensorflow 1.10.0](https://www.tensorflow.org/versions/r1.10/api_docs/python/tf/keras) for this version you have to use tensorflow.keras use ```import tensorflow as tf``` ```keras = tf.keras``` for oneline conversion from pure keras to tensorflow keras – Ramesh Kamath Jul 04 '19 at 06:10
  • 1
    `from tensorflow import keras` is identical, right? – endolith Aug 25 '20 at 15:35
5

To make it simple I will take the two versions of the code in keras and tf.keras. The example here is a simple Neural Network Model with different layers in it.

In Keras (v2.1.5)

from keras.models import Sequential
from keras.layers import Dense

def get_model(n_x, n_h1, n_h2):
    model = Sequential()
    model.add(Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(Dense(n_h2, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4, activation='softmax'))
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())
    return model

In tf.keras (v1.9)

import tensorflow as tf

def get_model(n_x, n_h1, n_h2):
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(tf.keras.layers.Dense(n_h2, activation='relu'))
    model.add(tf.keras.layers.Dropout(0.5))
    model.add(tf.keras.layers.Dense(4, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())

    return model

or it can be imported the following way instead of the above-mentioned way

from tensorflow.keras.layers import Dense

The official documentation of tf.keras

Note: TensorFlow Version is 1.9

Ruthwik
  • 545
  • 1
  • 8
  • 14
5

Starting from TensorFlow 2.0, only PyCharm versions > 2019.3 are able to recognise tensorflow and keras inside tensorflow (tensorflow.keras). Francois Chollet himself (author of Keras) recommends that everybody switches to tensorflow.keras in place of plain keras.

There is also one important mentioning here:

IMPORTANT NOTE FOR TF >= 2.0

There (this) is an ongoing issue with JetBrains (in fact from TensorFlow side), it seems that this error comes up from time to time (https://youtrack.jetbrains.com/issue/PY-53599).

It sometimes happens that PyCharm is not able to correctly import/recognize keras inside tensorflow or other imports.

Depending on Python + TF + PyCharm versions, you may have to alternate between the following import types:

from tensorflow.keras.models import Model

OR

from tensorflow.python.keras.models import Model
Timbus Calin
  • 13,809
  • 5
  • 41
  • 59
5

Its not quite fine to downgrade everytime, you may need to make following changes as shown below:

Tensorflow

import tensorflow as tf

#Keras
from tensorflow.keras.models import Sequential, Model, load_model, save_model
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.layers import Dense, Activation, Dropout, Input, Masking, TimeDistributed, LSTM, Conv1D, Embedding
from tensorflow.keras.layers import GRU, Bidirectional, BatchNormalization, Reshape
from tensorflow.keras.optimizers import Adam

from tensorflow.keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding
from tensorflow.keras import optimizers
from tensorflow.keras.callbacks import ModelCheckpoint

The point is that instead of using

from keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding

you need to add

from tensorflow.keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding
Shaina Raza
  • 1,474
  • 17
  • 12
2

this worked for me in tensorflow==1.4.0

from tensorflow.python import keras

Umair Qadir
  • 384
  • 3
  • 7
1

I have a similar problem importing those libs. I am using Anaconda Navigator 1.8.2 with Spyder 3.2.8.

My code is the following:

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import math

#from tf.keras.models import Sequential  # This does not work!
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import InputLayer, Input
from tensorflow.python.keras.layers import Reshape, MaxPooling2D
from tensorflow.python.keras.layers import Conv2D, Dense, Flatten

I get the following error:

from tensorflow.python.keras.models import Sequential

ModuleNotFoundError: No module named 'tensorflow.python.keras'

I solve this erasing tensorflow.python

With this code I solve the error:

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import math

#from tf.keras.models import Sequential  # This does not work!
from keras.models import Sequential
from keras.layers import InputLayer, Input
from keras.layers import Reshape, MaxPooling2D
from keras.layers import Conv2D, Dense, Flatten
pfRodenas
  • 326
  • 1
  • 2
  • 12
  • 3
    I believe this is only working because you also have the standalone keras package installed. This isn't actually using the keras that comes with tensorflow. – Bryan Head Apr 10 '18 at 16:23
  • 1
    @BryanHead is right. You can check your tensorflow version by `pip show tensorflow` – MeadowMuffins May 21 '18 at 09:43
  • 1
    It is actually solved when using `from tensorflow.keras.layers` because there are the modules exposed. The `tensorflow.python` package is in some ways private. – phi Apr 17 '19 at 07:47
1

I had the same problem with Tensorflow 2.0.0 in PyCharm. PyCharm did not recognize tensorflow.keras; I updated my PyCharm and the problem was resolved!

1

use below, if you are running on pycharm environment (observed for tensorflow==2.13.0)

import tensorflow as tf
import tensorflow 

from tensorflow.python import keras
from keras.layers import Dense
Rishabh Vatsa
  • 21
  • 1
  • 4