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

Rub*_*res 10 python tensorflow tensorflow-estimator tf.keras

I'm using Tensorflow==2.0.0a0 and want to run the following script:

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))
    ])
Run Code Online (Sandbox Code Playgroud)

All my older notebooks work with TF 1.13. However, I want to develop a notebook where I use Model Optimization (Neural net pruning) + TF Probability, which require Tensorflow > 1.13.

All libraries are imported but init = tf.global_variables_initializer() generates the error:

AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'
Run Code Online (Sandbox Code Playgroud)

Also, tf.Session() generates the error:

AttributeError: module 'tensorflow' has no attribute 'Session'
Run Code Online (Sandbox Code Playgroud)

So I guess it may be something related to Tensorflow itself, but I don't have older versions confliciting in my Anaconda environment.

Outputs for libraries' versions:

tf.__version__
Out[16]: '2.0.0-alpha0'

tfp.__version__
Out[17]: '0.7.0-dev20190517'

keras.__version__
Out[18]: '2.2.4-tf'
Run Code Online (Sandbox Code Playgroud)

Any ideas on this issue ?

y.s*_*hyk 10

Tensorflow 2.0 脱离会话并切换到急切执行。如果您参考 tf.compat 库并禁用 Eager Execution,您仍然可以使用 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))
    ])
Run Code Online (Sandbox Code Playgroud)

您可以使用以下方式以这种方式转换任何 python 脚本:

tf_upgrade_v2 --infile in.py --outfile out.py
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@y.selivonchyk。我使用 `import tensorflow.compat.v1 as tf`+ `tf.disable_v2_behavior()` 并照常保留代码 (2认同)