Tensorflow == 2.0.0a0-AttributeError:模块'tensorflow'没有属性'global_variables_initializer'

时间:2019-05-17 20:13:58

标签: python tensorflow tensorflow-estimator tf.keras

我正在使用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概率,这需要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'

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

3 个答案:

答案 0 :(得分:1)

Tensorflow 2.0脱离了会话,转而渴望执行。如果您引用tf.compat库并禁用急切执行,仍然可以使用会话运行代码:

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

答案 1 :(得分:0)

我相信TF 2.0已删除了“ Session()”。

相反,使用函数绘制图表(根据TensorFlow文档): https://www.tensorflow.org/alpha/tutorials/eager/tf_function

类似问题的日志:https://github.com/tensorflow/community/pull/20/commits/9645a1249d3bdbe8e930af62d1958120a940c31d

答案 2 :(得分:0)

使用这个

init = tf.compat.v1.global_variables_initializer()

如果在此之后出现错误,则运行以下内容

tf.compat.v1.disable_eager_execution()
init = tf.compat.v1.global_variables_initializer()