Tensorflow==2.0.0a0 - AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer' Tensorflow==2.0.0a0-属性错误:模块“tensorflow”没有“global_variables_initializer”属性。

11

我正在使用 Tensorflow==2.0.0a0 并希望运行以下脚本:

import tensorflow as tf
import tensorboard
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_probability as tfp
from tensorflow_model_optimization.sparsity import keras as sparsity
from tensorflow import keras

tfd = tfp.distributions

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    model = tf.keras.Sequential([
      tf.keras.layers.Dense(1,kernel_initializer='glorot_uniform'),
      tfp.layers.DistributionLambda(lambda t: tfd.Normal(loc=t, scale=1))
    ])

我所有的旧笔记本都可以使用TF 1.13。然而,我想开发一个笔记本,在其中使用模型优化(神经网络修剪)+ TF Probability,这需要 Tensorflow > 1.13

所有库都已导入,但是init = tf.global_variables_initializer()会生成错误:

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

此外,tf.Session() 会生成错误:
AttributeError: module 'tensorflow' has no attribute 'Session'

所以我猜可能与Tensorflow本身有关,但是在我的Anaconda环境中没有冲突的旧版本。

库版本的输出:

tf.__version__
Out[16]: '2.0.0-alpha0'

tfp.__version__
Out[17]: '0.7.0-dev20190517'

keras.__version__
Out[18]: '2.2.4-tf'

有关这个问题有什么想法吗?

在 GitHub 论坛上,我看到有人提到了 pip3 install --upgrade --force-reinstall tensorflow-gpu ... 另外,您使用的是哪个版本的 Python?也许您需要使用更新的版本? - smitty_werbenjagermanjensen
由于你正在使用tensorflow版本2.0.x.x,你不再需要使用tf.global_variables_initializer。请查看此迁移指南链接 - vb_rises
1
完美,@Vishal,我接受你的答案为最佳。问题已解决。 - razimbres
3个回答

13

Tensorflow 2.0放弃了会话(session)并转向即时执行(eager execution)。如果你参考tf.compat库并禁用eager execution,仍然可以使用会话运行代码:

import tensorflow as tf
import tensorboard
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_probability as tfp
from tensorflow_model_optimization.sparsity import keras as sparsity
from tensorflow import keras


tf.compat.v1.disable_eager_execution()


tfd = tfp.distributions

init = tf.compat.v1.global_variables_initializer()

with tf.compat.v1.Session() as sess:
    sess.run(init)

    model = tf.keras.Sequential([
      tf.keras.layers.Dense(1,kernel_initializer='glorot_uniform'),
      tfp.layers.DistributionLambda(lambda t: tfd.Normal(loc=t, scale=1))
    ])

您可以使用以下方式将任何Python脚本进行转换:
tf_upgrade_v2 --infile in.py --outfile out.py

4
感谢@y.selivonchyk,我使用了import tensorflow.compat.v1 as tf+ tf.disable_v2_behavior(),并像往常一样保留了代码。 - razimbres

1

0
使用这个。
init = tf.compat.v1.global_variables_initializer()

如果您在此之后遇到错误,请运行以下内容
tf.compat.v1.disable_eager_execution()
init = tf.compat.v1.global_variables_initializer()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接