Skip to main content
 首页 » 编程设计

python之Tensorflow==2.0.0a0之属性错误 : module 'tensorflow' has no attribute 'global_variables_initializer'

2024年11月24日30sky-heaven

我正在使用 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' 

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

请您参考如下方法:

Tensorflow 2.0 脱离 session 并切换到即时执行。如果您引用 tf.compat 库并禁用即时执行,您仍然可以使用 session 运行代码:

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