在https://allennlp.org/elmo中提供了预训练的ELMo模型。
我将如何使用提供的文件?
我认为我必须从json文件重构模型,然后将.hdf5文件的权重加载到模型中。
但是json格式似乎不适用于keras.models.model_from_json
。我得到了错误:ValueError: Improper config format: ...
最佳答案
使用tensorflow_hub
加载ELMo模型,例如:
import tensorflow as tf
import tensorflow_hub as hub
from keras.layers import Lambda
from keras.models import Input
from keras import backend as K
sess = tf.Session()
K.set_session(sess)
batch_size = 64
max_len = 100
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_x = Input(shape=(max_len,), dtype=tf.string)
embedding = Lambda(ElmoEmbedding, output_shape=(max_len, 128))(input_x)