首页 > 解决方案 > 如何在使用 tf-hub 的 tf 2.0 Keras 中使用 ELMO 嵌入作为第一个嵌入层?

问题描述

我正在尝试建立一个使用嵌入的NER模型。所以我在本教程中遇到了困难并开始实施。我有很多错误,其中一些是:KerasELMO

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

def ElmoEmbedding(x):
    return elmo_model(inputs={"tokens": tf.squeeze(tf.cast(x, tf.string)),
                            "sequence_len": tf.constant(batch_size*[max_len])},signature="tokens",as_dict=True)["elmo"]

input_text = Input(shape=(max_len,), dtype=tf.string)
embedding = Lambda(ElmoEmbedding, output_shape=(None, 1024))(input_text)

它给了我 AttributeError: module 'tensorflow' has no attribute 'Session'。因此,如果我注释掉sess=代码并运行,它会给我AttributeError: module 'keras.backend' has no attribute 'set_session'.

再说一次,Elmo代码行给了我RuntimeError: Exporting/importing meta graphs is not supported when eager execution is enabled. No graph exists when eager execution is enabled..

我有以下配置:

tf.__version__
'2.3.1'

keras.__version__
'2.4.3'

import sys
sys.version
'3.8.3 (default, Jul  2 2020, 17:30:36) [MSC v.1916 64 bit (AMD64)]'

如何ELMO在 Keras 模型中使用嵌入?

标签: tensorflowkerasdeep-learningnlpnamed-entity-recognition

解决方案


您使用的是旧的 Tensorflow 1.x 语法,但您安装了 tensorflow 2。

这是在 TF2 中执行 elmo 的新方法 使用 tensorflow 提取 ELMo 特征并将它们转换为 numpy


推荐阅读