Python 如何修复“AttributeError:模块'tensorflow'没有属性'get_default_graph'”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/55496289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix "AttributeError: module 'tensorflow' has no attribute 'get_default_graph'"?
提问by Alice
I am trying to run some code to create an LSTM model but i get an error:
我正在尝试运行一些代码来创建 LSTM 模型,但出现错误:
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'
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!
我发现其他人有类似的问题,他们更新了 tensorflow 并且它有效;但我的是最新的,仍然无法正常工作。我是使用 keras 和机器学习的新手,所以如果这很愚蠢,我深表歉意!
采纳答案by Alice
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.
结果我使用了错误的版本 (2.0.0a0),所以我重置到最新的稳定版本 (1.13.1) 并且它可以工作。
回答by irezwi
Please try:
请尝试:
from tensorflow.keras.models import Sequential
from tensorflow.keras.models import Sequential
instead of
代替
from keras.models import Sequential
from keras.models import Sequential
回答by Sana
for latest tensorflow 2 replace the above code with below code with some changes
对于最新的 tensorflow 2,将上面的代码替换为下面的代码,并进行一些更改
for details check keras documentation: https://www.tensorflow.org/guide/keras/overview
有关详细信息,请查看 keras 文档: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'])
回答by Piyush Chandra
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.
是的,它不会工作,因为您使用的是 tensorflow 的更新版本,即 tensorflow == 2.0 ,旧版本的 tensorflow 可能会有所帮助。我遇到了同样的问题,但我使用以下代码修复了它。
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
回答by palandlom
For tf 2.1.0 I change to tf.compat.v1.get_default_graph()
对于 tf 2.1.0 我改为 tf.compat.v1.get_default_graph()
import tensorflow as tf
# sess = tf.compat.v1.Session(graph=tf.import_graph_def(), config=session_conf)
sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)
tf.compat.v1.keras.backend.set_session(sess)
回答by Jomo
to solve the problem i used the code below
为了解决这个问题,我使用了下面的代码
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import numpy
从 tensorflow.keras.models 导入顺序从 tensorflow.keras.layers 导入密集导入 numpy
回答by Hamidreza
Assuming people referring to this thread will be using more and more tensorflow 2:
假设人们参考此线程将使用越来越多的 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:
Tensorflow 2 进一步集成了 keras api,因为 keras 的设计/开发非常明智。答案是如果你正在使用tensorflow 2非常容易,也说明这里:
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;
这就是你如何改变一个人会使用来自keras官方页面的MNIST之类的东西,只需替换tensorflow.keras
而不是 keras
在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])
回答by yash
Use the following:
使用以下内容:
tf.compat.v1.disable_eager_execution()
print(tf.compat.v1.get_default_graph())
It works for tensorflow 2.0
它适用于 tensorflow 2.0
回答by Hannah Zhang
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:
他们都没有工作。所以我更新了 tensorflow、keras 和 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:
我的 tensorflow 版本是 2.1.0;我的 keras 版本是 2.3.1;我的 python 版本是 3.6.10。在我卸载 keras 并重新安装 keras 之前,什么都不起作用:
pip uninstall keras
pip install keras --upgrade
回答by mj.beyrami
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
降级将解决该问题,但如果您想使用最新版本,则必须尝试以下代码:from tensorflow import keras
并且 'from tensorflow.python.keras import backend as k
这对我有用