一.配置环境
在你的环境中下载allennlp,这个包自带pytorch。所以你在自己的conda里面创建和虚拟环境之后,直接pip这个就行
pip install allennlp
下载好ELMo要用到的参数和模型
options.json(这个你复制进txt,然后把txt后缀改成json就OK了)
weights.hdf5
代码
from allennlp.modules.elmo import Elmo, batch_to_ids
options_file = "options.json" # 配置文件地址
weight_file = "weights.hdf5" # 权重文件地址
# 这里的1表示产生一组线性加权的词向量。
# 如果改成2 即产生两组不同的线性加权的词向量。
elmo = Elmo(options_file, weight_file, 1, dropout=0)
# use batch_to_ids to convert sentences to character ids
sentence_lists = [['I', 'love', 'you', '.'], ['Sorry', ',', 'I', 'don', "'t", 'love', 'you', '.']] #references
character_ids = batch_to_ids(sentence_lists)
embeddings = elmo(character_ids)['elmo_representations'][0]
elmo_mask = elmo(character_ids)['mask']
print(embeddings)
print(elmo_mask)
print(embeddings.size())
结果如下
torch.Size([2, 8, 1024])的意思是
2指的是batch
8指的是list最大长度
1024指的是每层输出的维度