python - 如何在交互模式下使用Elmo词嵌入与原始预训练模型(5.5B)

标签 python machine-learning nlp artificial-intelligence allennlp

我正在尝试通过本教程学习如何使用 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 )?

我不太明白为什么我们必须调用“assert”或者为什么我们在向量输出上使用 [2][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 是测试和确保变量特定值的便捷方法。这看起来像 a good resource阅读更多内容。例如,第一个 assert 语句确保嵌入具有三个输出矩阵。


接下来,我们使用 [i][j] 进行索引,因为模型输出 3 层矩阵(我们选择第 i 个),并且每个矩阵都有 n code> tokens(我们选择第 j 个)每个长度为 1024。请注意代码如何比较“apple”和“carrot”的相似度,这两个 token 都是索引 j=3 处的第 4 个 token。从示例文档中,i 代表以下之一:

The first layer corresponds to the context insensitive token representation, followed by the two LSTM layers. See the ELMo paper or follow up work at EMNLP 2018 for a description of what types of information is captured in each layer.

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


最后,如果您有一组句子,使用 ELMO,您不需要对标记向量进行平均。该模型是一个基于字符的 LSTM,它在标记化的整个句子上运行得非常好。使用专为处理句子集而设计的方法之一:embed_sentences()embed_batch() 等。 More in the code !

关于python - 如何在交互模式下使用Elmo词嵌入与原始预训练模型(5.5B),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54000564/

相关文章:

python - 如何在 Python 中绘制多元函数?

python - 在 OSX 中的另一个应用程序上触发放置事件

python - 可靠地将大文件上传到 Google 云端硬盘

python - 如何将机器学习与 Firebase 数据结构结合使用?

machine-learning - 是否可以通过 API 将自定义模型导入到 WDS 中?

python - 自然语言处理 : text corpus format for word2vec

python - 如果我们仍然需要检查每个项目,哈希的含义是什么?

r - 有没有办法在不同版本的 H2O 之间使用保存的模型?

python - Spacy 使用什么来创建向量表示?

nlp - 将一个有多个主语的复合句分成多个各有一个主语的句子?