问题
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!
回答1:
Please try:
from tensorflow.keras.models import Sequential
instead of
from keras.models import Sequential
回答2:
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.
回答3:
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'])
回答4:
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
回答5:
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.
回答6:
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.
来源:https://stackoverflow.com/questions/55496289/how-to-fix-attributeerror-module-tensorflow-has-no-attribute-get-default-gr