Tensorflow==2.0.0a0 - AttributeError:模块“tensorflow”没有属性“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。但是,我想开发一个使用模型优化(神经网络修剪)+ 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'

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

原文由 razimbres 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 580
2 个回答

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

原文由 y.selivonchyk 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

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

原文由 N.Yasarturk 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题