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!
19 Answers
Please try:
from tensorflow.keras.models import Sequential
instead of
from keras.models import Sequential
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) 0for latest tensorflow 2 replace the above code with below code with some changes
for details check keras documentation:
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']) It occurs due to changes in tensorflow version :: Replace
tf.get_default_graph() by
tf.compat.v1.get_default_graph() 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 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.
2Replace all keras.something.something with tensorflow.keras.something, and use:
import tensorflow as tf from tensorflow.keras import backend as k 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
Use the following:
tf.compat.v1.disable_eager_execution() print(tf.compat.v1.get_default_graph()) It works for tensorflow 2.0
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 To solve the problem I used the code below:
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import numpy 1!pip uninstall tensorflow !pip install tensorflow==1.14 this worked for me... working on hrnetv2.. ty
This worked for me. Please use the below import
from tensorflow.keras.layers import Input 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.
1Yes, the code is not working with this version of tensorflow tensorflow == 2.0.0 . moving to version older than 2.0.0 will help.
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]) 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.
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
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']) 1and voila!!