How to fix "AttributeError: module 'tensorflow' has no attribute 'get_default_graph'"?

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!


Solution 1:

Please try:

from tensorflow.keras.models import Sequential

instead of

from keras.models import Sequential

Solution 2:

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)