2

我正在尝试通过本教程学习如何使用 Elmo 嵌入:

https://github.com/allenai/allennlp/blob/master/tutorials/how_to/elmo.md

我特别尝试使用如下所述的交互模式:

$ ipython
> from allennlp.commands.elmo import ElmoEmbedder
> elmo = ElmoEmbedder()
> tokens = ["I", "ate", "an", "apple", "for", "breakfast"]
> vectors = elmo.embed_sentence(tokens)

> assert(len(vectors) == 3) # one for each layer in the ELMo output
> assert(len(vectors[0]) == len(tokens)) # the vector elements 
correspond with the input tokens

> import scipy
> vectors2 = elmo.embed_sentence(["I", "ate", "a", "carrot", "for", 
"breakfast"])
> scipy.spatial.distance.cosine(vectors[2][3], vectors2[2][3]) # cosine 
distance between "apple" and "carrot" in the last layer
0.18020617961883545

我的总体问题是如何确保在原始 5.5B 集上使用预训练的 elmo 模型(在此处描述:https ://allennlp.org/elmo )?

我不太明白为什么我们必须调用“断言”或为什么我们在向量输出上使用 [2][3] 索引。

我的最终目的是平均所有词嵌入以获得句子嵌入,所以我想确保我做对了!

感谢您的耐心等待,因为我对这一切都很陌生。

4

1 回答 1

3

默认情况下,ElmoEmbedder使用来自 1 Bil Word 基准的预训练模型的原始权重和选项。大约 8 亿个代币。为确保您使用的是最大的模型,请查看ElmoEmbedder该类的参数。从这里您可能会发现您可以设置模型的选项和权重:

elmo = ElmoEmbedder(
    options_file='https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway_5.5B/elmo_2x4096_512_2048cnn_2xhighway_5.5B_options.json', 
    weight_file='https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway_5.5B/elmo_2x4096_512_2048cnn_2xhighway_5.5B_weights.hdf5'
)

我从 AllenNLP 提供的预训练模型表中获得了这些链接。


assert是一种方便的方法来测试和确保变量的特定值。这看起来是阅读更多内容的好资源。例如,第一assert条语句确保嵌入具有三个输出矩阵。


在此基础上,我们使用索引,[i][j]因为模型输出 3 层矩阵(我们选择第 i 个)并且每个矩阵都有n长度为 1024 的标记(我们选择第 j 个)。注意代码如何比较相似性“apple”和“carrot”,它们都是索引 j=3 处的第 4 个标记。在示例文档中, i 代表以下之一:

第一层对应于上下文不敏感的令牌表示,然后是两个 LSTM 层。请参阅 ELMo 论文或 EMNLP 2018 的后续工作,了解每层捕获的信息类型。

该论文提供了这两个 LSTM 层的详细信息。


最后,如果你有一组句子,使用 ELMO 你不需要对标记向量进行平均。该模型是一个基于字符的 LSTM,它在标记化的整个句子上工作得非常好。使用为处理句子集而设计的一种方法:embed_sentences()、、embed_batch()等。更多在代码中

于 2019-01-03T22:13:18.090 回答