elmoformanylangs网址:https://github.com/HIT-SCIR/ELMoForManyLangs
需要预先准备的环境:
-
python >= 3.6
-
torch
-
allennlp
安装过程
elmoformanylangs是基于allennlp开发的库,而torch是allennlp的重要依赖包,所以首先需要安装torch,直接用pip install torch来安装好像不行,我先去下载whl文件,然后才安装
安装torch
torch下载地址:https://download.pytorch.org/whl/torch_stable.html
下载好之后,在命令行定位到whl文件的目录下,输入以下命令安装:
pip install 文件名
安装allennlp
成功安装torch之后,就可以安装allennlp了,本以为直接pip install allennlp就完事了,但是总是报错,报错内容大概是:No match distribution found for torch1.6.0,我:???明明已经安装好torch了呀,至今还不知道为什么。后来在allennlp后面加了版本号,就ok了(还是想知道之前为什么报错)
pip install allennlp==1.1.0rc3
安装elmoformanylangs
elmoformanylangs库可以用简单的几行代码就生成elmo词向量。
github网址:https://github.com/HIT-SCIR/ELMoForManyLangs
可以去网址把代码下载下来,也可以点击这里下载
下载解压之后,命令行定位到setup.py目录下,用以下命令安装
python setup.py install
中文模型使用方法
elmoformanylangs提供了多钟语言的模型,这里以中文模型为例
下载解压之后,将config.json文件下的“config_path”的值里面那两个点和斜杠去掉,然后把整个zhs.model文件夹拖进项目里即可使用。
修改后:
"config_path": "configs/cnn_50_100_512_4096_sample.json"
将zhs.model拖入项目中
生成词向量
from elmoformanylangs import Embedder
e = Embedder(r'zhs.model/')
sents = [['今', '天', '天氣', '真', '好', '阿'],
['潮水', '退', '了', '就', '知道', '誰', '沒', '穿', '褲子']]
# the list of lists which store the sentences
# after segment if necessary.
e.sents2elmo(sents)
# will return a list of numpy arrays
# each with the shape=(seq_len, embedding_size)
显然,sents是一个列表,存放的是每一个句子分词之后的词列表。最后将这个sents列表用对应的方法即可生成词向量,词向量格式是numpy的ndarray格式