user11749375
user11749375

Reputation:

How to write the code to avoid the error of 'tensorflow' has no attribute 'Session' and 'global_variables_initializer'

Trying to run a sample code for a Named Entity Recognition model as apractice.

The reference article is: Named Entity Recognition (NER) with keras and tensorflow

github: https://github.com/nxs5899/Named-Entity-Recognition_DeepLearning-keras

However, I have stacked with version difference of tensorflow version.

Since I'm not familiar with Tensorflow, I cannot modify the sample code following the description of the change.

I'd also appreciate it if you could share helpful articles or GitHub to build a Named Entity Recognition model with original data.

Error Message

---> 11 sess = tf.Session()
     12 K.set_session(sess)

AttributeError: module 'tensorflow' has no attribute 'Session'

Working Code

from sklearn.model_selection import train_test_split
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.keras.backend import eval

X_tr, X_te, y_tr, y_te = train_test_split(new_X, y, test_size=0.1, random_state=2018)
batch_size = 32
import tensorflow as tf
import tensorflow_hub as hub
from keras import backend as K
sess = tf.Session()
K.set_session(sess)

elmo_model = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True)
sess.run(tf.global_variables_initializer())
sess.run(tf.tables_initializer())

What I tried to do

Following the related question about Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session', I tried to fix my code, but another error was shown.

If it is because of my trial fixed code, I would like to how should I write for the new version of tensorflow.

Another Error

module 'tensorflow' has no attribute 'global_variables_initializer'

fixed version

from sklearn.model_selection import train_test_split
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.keras.backend import eval

tf.compat.v1.disable_eager_execution()

X_tr, X_te, y_tr, y_te = train_test_split(new_X, y, test_size=0.1, random_state=2018)
batch_size = 32
import tensorflow as tf
import tensorflow_hub as hub
from keras import backend as K
sess = tf.compat.v1.Session()
K.set_session(sess)

elmo_model = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True)
sess.run(tf.global_variables_initializer())
sess.run(tf.tables_initializer())

Upvotes: 0

Views: 855

Answers (1)

user11530462
user11530462

Reputation:

To execute your code in Tensorflow 2.x, you can try as shown below

from sklearn.model_selection import train_test_split
import tensorflow as tf
import tensorflow_hub as hub

X_tr, X_te, y_tr, y_te = train_test_split(new_X, y, test_size=0.1, random_state=2018)

elmo_model = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True)

Upvotes: 0

Related Questions