Tensorflow==2.0.0a0 - AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'

Tensorflow==2.0.0a0 - AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'

我正在使用 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。但是,我想开发一个使用模型优化(神经网络 p运行ing)+ 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'

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

我相信 "Session()" 已从 TF 2.0 中删除。

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

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

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

使用这个

init = tf.compat.v1.global_variables_initializer()

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

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