📜  使用语言模型 (ELMo) 嵌入的词嵌入概述(1)

📅  最后修改于: 2023-12-03 14:49:57.789000             🧑  作者: Mango

使用语言模型 (ELMo) 嵌入的词嵌入概述

ELMo (Embeddings from Language Models) 是一种有效的词嵌入方法,它是使用深度双向语言模型 (deep bidirectional language model) 训练的。ELMo 模型的主要特点是它可以用于根据上下文识别词汇的多个含义,因此它是一种上下文化词嵌入 (contextualized embeddings),与其他词嵌入方法相比,ELMo 是一种最新的,并且可以提供更好的性能。

ELMo 模型的原理

ELMo 模型的工作原理是首先使用双向语言模型来捕捉文本的左右语境,然后使用反向语言模型来捕捉文本的右左语境,以此来生成每个词的表示形式。具体地说,ELMo 模型使用残差连接(residual connections)和黑箱深度组合(deep compositional architecture)的组合方式,生成文本的上下文化表示形式。

ELMo 模型的使用

要使用 ELMo 模型,您需要安装 TensorFlow 并下载预训练的模型,然后使用以下代码加载模型:

import tensorflow_hub as hub

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

加载模型后,您可以使用以下代码来获取文本的 ELMo 嵌入:

# 要处理的文本
sentences = ["Machine learning is awesome!", "I love coding in Python!"]

# 将文本转换为 ELMo 嵌入
embeddings = elmo(sentences, signature="default", as_dict=True)["elmo"]

请注意,模块返回的张量 (Tensor) 的形状是(句子,最大单词数,ELMo 嵌入维度)。如果您要处理的每个句子的最大单词数不同,则需要使用填充方式来确保它们具有相同的大小。使用 TensorFlow 就很容易了:

import tensorflow as tf

max_length = max([len(sentence.split(" ")) for sentence in sentences])
padded_sentences = [sentence + " " * (max_length - len(sentence.split(" "))) for sentence in sentences]

# 将文本转换为 ELMo 嵌入
embeddings = elmo(padded_sentences, signature="default", as_dict=True)["elmo"]

# 删除添加的填充
mask = tf.sequence_mask([len(sentence.split(" ")) for sentence in sentences], max_length)
mask = tf.cast(mask, tf.float32)
embeddings = embeddings * tf.expand_dims(mask, -1)
总结

ELMo 模型是一种上下文化词嵌入方法,可以为自然语言处理任务提供更好的性能。要使用 ELMo 模型,请下载预训练模型并使用 TensorFlow 加载它。 然后,您可以使用模型来生成文本的 ELMo 嵌入。