如何编写代码以避免'tensorflow'没有属性'Session'和'global_variables_initializer'的错误

Posted

技术标签:

【中文标题】如何编写代码以避免\'tensorflow\'没有属性\'Session\'和\'global_variables_initializer\'的错误【英文标题】:How to write the code to avoid the error of 'tensorflow' has no attribute 'Session' and 'global_variables_initializer'如何编写代码以避免'tensorflow'没有属性'Session'和'global_variables_initializer'的错误 【发布时间】:2021-09-16 04:28:50 【问题描述】:

尝试为命名实体识别模型运行示例代码作为实践。

参考文章为:Named Entity Recognition (NER) with keras and tensorflow

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

但是,我已经叠加了 tensorflow 版本的版本差异。

由于对Tensorflow不熟悉,无法按照变更说明修改示例代码。

如果您能分享有用的文章或 GitHub 以使用原始数据构建命名实体识别模型,我将不胜感激。

错误信息

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

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

工作代码

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())

我想做什么

根据有关Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' 的相关问题,我尝试修复我的代码,但显示了另一个错误。

如果是因为我的试用固定代码,我想请问新版tensorflow应该怎么写。

另一个错误

module 'tensorflow' has no attribute 'global_variables_initializer'

固定版本

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())

【问题讨论】:

您尝试运行的代码是为 TensorFlow v1.x 编写的,并且您使用的是 TF v2.x。请参阅differences between TF1 and TF2 和guide to migrate 的答案(如果您愿意)。 【参考方案1】:

要在 Tensorflow 2.x 中执行你的代码,你可以尝试如下所示

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)

【讨论】:

以上是关于如何编写代码以避免'tensorflow'没有属性'Session'和'global_variables_initializer'的错误的主要内容,如果未能解决你的问题,请参考以下文章

好或坏:制作巨型结构以避免使用结构的全局/属性/大量参数

如何动态添加struct属性以避免冗余代码? [关闭]

如何避免两次编写 SQL Server 查询以避免重复?

如何强制 keras 使用 tensorflow GPU 后端

如何避免在 TensorFlow 中添加重复的集合?

如何修复 AttributeError:模块 'tensorflow' 没有属性 'keras'?