首页 > 解决方案 > AttributeError:模块“tensorflow”没有属性“get_default_graph”

问题描述

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.

为什么我会收到此错误?

标签: tensorflow

解决方案


看起来您正在使用 TensorFlow 2.0(或更新的版本)。TensorFlow >= 2.0 在tf.keras. 正如Keras 网站上所述,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


推荐阅读