TensorFlow版本问题的解决方案(module ‘tensorflow‘ has no attribute ×××、The Session graph is empty等)

假设有以下代码:


import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
import tf_utils
import time

np.random.seed(1)

y_hat = tf.constant(36, name='y_hat')# 定义y_hat为固定值36
y = tf.constant(39, name='y')# 定义y为固定值39

loss = tf.Variable((y - y_hat) ** 2, name='loss')# 为损失函数创建一个变量

init = tf.global_variables_initializer()# 运行之后的初始化(session.run(init))
                                                  # 损失变量将被初始化并准备计算
with tf.Session() as session:                   # 创建一个session并打印输出
    session.run(init)                           # 初始化变量
    print(session.run(loss))                    # 打印损失值

我们运行它,结果会报错如下:
TensorFlow版本问题的解决方案(module ‘tensorflow‘ has no attribute ×××、The Session graph is empty等)_第1张图片

Traceback (most recent call last):
File “D:/PyCharm/Projects/DL_Courses_By_Wuenda/Class_2_Week_3/temp.py”, line 19, in
init = tf.global_variables_initializer()# 运行之后的初始化(session.run(init))
AttributeError: module ‘tensorflow’ has no attribute ‘global_variables_initializer’

我感觉这应该是就是TensorFlow当中存在的版本问题
另外,类似以下的报错我感觉也是版本问题:

RuntimeError: The Session graph is empty. Add operations to the graph before calling run().

AttributeError: module ‘tensorflow’ has no attribute ‘Session’

此时我们在import tensorflow as tf后面加一行代码:

import tensorflow.compat.v1 as tf

这行代码可能会报错,不用管它
再在np.random.seed(1)前面加一行代码:

tf.disable_v2_behavior()

然后再运行,报错解决:
TensorFlow版本问题的解决方案(module ‘tensorflow‘ has no attribute ×××、The Session graph is empty等)_第2张图片

贴下完整无报错代码:


import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.compat.v1 as tf
from tensorflow.python.framework import ops
import tf_utils
import time

tf.disable_v2_behavior()
np.random.seed(1)

y_hat = tf.constant(36, name='y_hat')# 定义y_hat为固定值36
y = tf.constant(39, name='y')# 定义y为固定值39

loss = tf.Variable((y - y_hat) ** 2, name='loss')# 为损失函数创建一个变量

init = tf.global_variables_initializer()# 运行之后的初始化(session.run(init))
                                                  # 损失变量将被初始化并准备计算
with tf.Session() as session:                   # 创建一个session并打印输出
    session.run(init)                           # 初始化变量
    print(session.run(loss))                    # 打印损失值

你可能感兴趣的:(TensorFlow踩坑,DeepLearning,tensorflow)