ELMo模型最简单使用方式(pytorch版)

一.配置环境

在你的环境中下载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指的是每层输出的维度

  • 6
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 22
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值