Python Tensorflow==2.0.0a0-属性错误:模块';tensorflow';没有属性';全局变量初始化器';
我正在使用Python Tensorflow==2.0.0a0-属性错误:模块';tensorflow';没有属性';全局变量初始化器';,python,tensorflow,tensorflow-estimator,tf.keras,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 spar
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))
])
我所有的旧笔记本都使用TF1.13。然而,我想开发一个笔记本,其中我使用模型优化(神经网络修剪)+TF概率,这需要Tensorflow>1.13
所有库都已导入,但init=tf。全局变量\u初始值设定项()
生成错误:
AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'
AttributeError: module 'tensorflow' has no attribute 'Session'
另外,tf.Session()
生成错误:
AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'
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'
关于这个问题有什么想法吗?我相信TF2.0已经删除了“Session()”
相反,使用函数绘制图形(根据TensorFlow文档):
类似问题的日志: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()
在GitHub论坛上,我看到上面提到的pip3安装--升级--强制重新安装tensorflow gpu。。。另外,您使用的是哪一版本的python?也许您需要使用更新的版本?因为您使用的是tensorflow veriso 2.0.x.x,所以您不再需要使用
tf.global\u variables\u initializer
。检查一下这本迁移指南,非常完美,@Vishal,我接受你的回答,认为这是最好的。解决了问题谢谢@y.selivonchyk。我使用了import tensorflow.compat.v1作为tf
+tf.disable\u v2\u behavior()
并像往常一样保留代码