tensorflow - 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 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
推荐阅读
- java - 在while循环中声明字符串变量,而不是整个循环 - java
- java - 在 Android 中使用 TextUtil 类优于 String 类有什么优势吗?
- python - Flask url_for 返回404(文件未找到),但绝对路径正确
- flutter - 颤振检查器不适用于我的 github 存储库中的应用程序
- python-3.x - 将列中的值与整数进行比较
- java - 使用 ArrayList 的挂钩方法
范围 - flutter - 检查输入的电话号码时,颤振表单验证不起作用
- xamarin - 有谁知道如何使 SfCalendar 的周视图漂亮?
- java - 如何在 Android 上使用 ServiceWorkerController
- python - Pygame:我的子弹类除了被绘制之外什么都不做