57

I am trying to run some code to create an LSTM model but i get an error:

AttributeError: module 'tensorflow' has no attribute 'get_default_graph'

My code is as follows:

from keras.models import Sequential

model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.add(LSTM(17))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

I have found someone else with a similar problem and they updated tensorflow and it works; but mine is up to date and still does not work. I am new to using keras and machine learning so I apologise if this is something silly!

Alice
  • 643
  • 1
  • 5
  • 7

19 Answers19

48

Please try:

from tensorflow.keras.models import Sequential

instead of

from keras.models import Sequential

Majid
  • 13,853
  • 15
  • 77
  • 113
irezwi
  • 789
  • 8
  • 14
23

For tf 2.1.0 I used tf.compat.v1.get_default_graph() - e.g:

import tensorflow as tf
sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)
tf.compat.v1.keras.backend.set_session(sess)

palandlom
  • 529
  • 6
  • 17
13

for latest tensorflow 2 replace the above code with below code with some changes

for details check keras documentation: https://www.tensorflow.org/guide/keras/overview

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential, load_model

model = tf.keras.Sequential()
model.add(layers.Dense(32, input_dim=784))
model.add(layers.Activation('relu'))
model.add(layers.LSTM(17))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(0.01), metrics=['accuracy'])
Sergey Shubin
  • 3,040
  • 4
  • 24
  • 36
SKB
  • 771
  • 7
  • 14
10

It occurs due to changes in tensorflow version :: Replace

tf.get_default_graph()

by

tf.compat.v1.get_default_graph()
Stefan
  • 1,697
  • 15
  • 31
Sooraj S
  • 399
  • 4
  • 5
6

I had the same problem. I tried

from tensorflow.keras.models import Sequential

and

from keras.models import Sequential

none of them works. So I update tensorflow, keras and python:

$conda update python
$conda update keras
$conda update tensorflow

or

pip install --upgrade tensorflow
pip install --upgrade keras
pip install --upgrade python

My tensorflow version is 2.1.0; my keras version is 2.3.1; my python version is 3.6.10. Nothing works until I unintall keras and reinstall keras:

pip uninstall keras
pip install keras --upgrade
Sergey Shubin
  • 3,040
  • 4
  • 24
  • 36
Hannah Zhang
  • 489
  • 5
  • 5
5

Turns out I was using the wrong version (2.0.0a0), so i reset to the latest stable version (1.13.1) and it works.

Alice
  • 643
  • 1
  • 5
  • 7
  • 1
    This isn't a solution, you went back to an earlier version of keras and used that version's implementation. @irezwi 's answer is the one that worked with tf 2.0 – MuhsinFatih Oct 24 '19 at 22:45
  • 1
    Just to add a little more explanation: TensorFlow 2.0 has Keras built-in; no need to load Keras separately into your environment; just change the import statements as @irezwi shows. – jhughs Nov 08 '19 at 19:00
4

Replace all keras.something.something with tensorflow.keras.something, and use:

import tensorflow as tf
from tensorflow.keras import backend as k
Run_Script
  • 2,487
  • 2
  • 15
  • 30
Nixon D
  • 41
  • 1
2

Use the following:

tf.compat.v1.disable_eager_execution()
print(tf.compat.v1.get_default_graph())

It works for tensorflow 2.0

sshashank124
  • 31,495
  • 9
  • 67
  • 76
yash
  • 311
  • 3
  • 2
1

Downgrading will fix the problem but if you want to use latest version, you must try this code: from tensorflow import keras and 'from tensorflow.python.keras import backend as k That's work for me

mj.beyrami
  • 49
  • 1
  • 7
1

To solve the problem I used the code below:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy
ah bon
  • 9,293
  • 12
  • 65
  • 148
Jomo
  • 11
  • 1
  • 1
    Hi, welcome to Stackoverflow and thanks for your reply! Please add what you think may have caused the error and what's the idea behind your solution so others may understand the underlying concepts and find solutions in similar cases! Also please use the formatting options, e.g. to make cod examples stand out! You can use the icons on top of the edit area, as well as markup—documentation is available by click on the help icon in the top right corner of the edit area. – Amadán Feb 19 '20 at 13:00
1

YES, it won't work since you are using the updated version of tensorflow ie tensorflow == 2.0 , the older version of tensorflow might help. I had the same problem but i fixed it using the following code.

try:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout

instead:

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
Piyush Chandra
  • 159
  • 1
  • 4
1
!pip uninstall tensorflow 
!pip install tensorflow==1.14

this worked for me... working on hrnetv2.. ty

Bharath Kumar
  • 893
  • 9
  • 8
1

This worked for me. Please use the below import

from tensorflow.keras.layers import Input
viraj ghorpade
  • 473
  • 5
  • 8
0

This has also happend to me. The reason is your tensorflow version. Try to get older version of tensorflow. Another problem can be you have a python script named tensorflow.py in your project.

Gihan Gamage
  • 2,944
  • 19
  • 27
0

Yes, the code is not working with this version of tensorflow tensorflow == 2.0.0 . moving to version older than 2.0.0 will help.

poonam
  • 1
  • 1
0

Assuming people referring to this thread will be using more and more tensorflow 2:

Tensorflow 2 integrates further keras api, since keras is designed/developed very wisely. The answer is very easy if you are using tensorflow 2, as described also here:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, LSTM

model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.add(LSTM(17))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss=tensorflow.keras.losses.binary_crossentropy, optimizer=tensorflow.keras.optimizers.Adam(), metrics=['accuracy'])

and that's how you change one would use something like MNIST from keras official page with just replacing tensorflow.keras instead of keras and runnig it also on gpu;

from __future__ import print_function
import tensorflow
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import backend as K

batch_size = 1024
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = tensorflow.keras.utils.to_categorical(y_train, num_classes)
y_test = tensorflow.keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
             activation='relu',
             input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=tensorflow.keras.losses.categorical_crossentropy,
          optimizer=tensorflow.keras.optimizers.Adadelta(),
          metrics=['accuracy'])

model.fit(x_train, y_train,
      batch_size=batch_size,
      epochs=epochs,
      verbose=1,
      validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
Shivid
  • 1,295
  • 1
  • 22
  • 36
0

For TensorFlow 2.0, use keras bundled with tensorflow.

try replacing keras.models with tensorflow.python.keras.models or tensorflow.keras.models:

from tensorflow.python.keras.models import Sequential

from tensorflow.python.keras.layers.core import Dense, Activation

This should solve the problem.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
0

To resolve version issues in TensorFlow, it's a good idea to use this below technique to import v1 (version 1 or TensorFlow 1. x) and we also can disable the TensorFlow 2. x behaviors.

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

You can refer to the following link to check the mapping between Tensorflow 1. x and 2. x

Debashis Sahoo
  • 5,388
  • 5
  • 36
  • 41
-1

Please try to be concise!

First -->

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

Then -->

model = keras.Sequential(
    [
        layers.Dense(layers.Dense(32, input_dim=784)),
        layers.Dense(activation="relu"),
        layers.Dense(LSTM(17))

    ]
)
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(0.01), metrics=['accuracy'])

and voila!!

  • Welcome to Stack Overflow! Please, make sure that your solution was not already proposed in another answers like [this one](https://stackoverflow.com/a/60476812/6682517). – Sergey Shubin Nov 02 '20 at 08:53