AttributeError:模块“ tensorflow”没有属性“ get_default_graph”

时间:2020-03-31 17:01:28

标签: tensorflow

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

model = Sequential([    Dense(32, activation='relu', input_shape=(5038,)),    Dense(32, activation='relu'),    Dense(881, activation='sigmoid'),])
model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
hist = model.fit(X_train, Y_train,          batch_size=32, epochs=100,          validation_data=(X_val, Y_val))

给出以下输出

AttributeError                            Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py in _get_default_graph()
     65     try:
---> 66         return tf.get_default_graph()
     67     except AttributeError:

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

During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
5 frames
/usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py in _get_default_graph()
     67     except AttributeError:
     68         raise RuntimeError(
---> 69             'It looks like you are trying to use '
     70             'a version of multi-backend Keras that '
     71             'does not support TensorFlow 2.0. We recommend '

RuntimeError: It looks like you are trying to use a version of multi-backend Keras that does not support TensorFlow 2.0. We recommend using `tf.keras`, or alternatively, downgrading to TensorFlow 1.14.

为什么会出现此错误?

1 个答案:

答案 0 :(得分:0)

您似乎正在使用TensorFlow 2.0(或更新的版本)。 TensorFlow> = 2.0在tf.keras下对Keras具有完整的内置支持。如Keras website所述,TensorFlow用户应使用tf.keras而不是Keras模块。

可以使用tf.keras通过以下方式重写您的特定示例:

import tensorflow as tf


model = tf.keras.Sequential([
    tf.keras.layers.Dense(32, activation='relu', input_shape=(5038,)), 
    tf.keras.layers.Dense(32, activation='relu'),
    tf.keras.layers.Dense(881, activation='sigmoid')])
model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
hist = model.fit(X_train, Y_train, batch_size=32, epochs=100, validation_data=(X_val, Y_val))

有关更多信息,请参见此处的tf.keras教程:https://www.tensorflow.org/tutorials