训练GloVe中文词向量

准备语料

准备好自己的语料,保存为txt,每行一个句子或一段话,注意要分好词。

准备源码在这里插入图片描述

从GitHub下载代码,https://github.com/stanfordnlp/GloVe
将语料corpus.txt放入到Glove的主文件夹下。

修改bash

打开demo.sh,修改相应的内容

因为demo默认是下载网上的语料来训练的,因此如果要训练自己的语料,需要注释掉
在这里插入图片描述

修改参数设置,将CORPUS设置成语料的名字

在这里插入图片描述
执行bash文件

进入到主文件夹下

make
在这里插入图片描述

bash demo.sh
在这里插入图片描述

注意,如果训练数据较大,则训练时间较长,那么建议使用nohup来运行程序

1
nohup bash demo.sh >output.txt 2>&1 &
坐等训练,最后会得到vectors.txt 以及其他的相应的文件。如果要用gensim的word2ve load进来,那么需要在vectors.txt的第一行加上vacob_size vector_size,第一个数指明一共有多少个向量,第二个数指明每个向量有多少维。

参考

https://www.cnblogs.com/echo-cheng/p/8561171.html

你可以在以下网站下载GloVe训练词向量: 1. Stanford NLP Group:https://nlp.stanford.edu/projects/glove/ 2. GitHub:https://github.com/stanfordnlp/GloVe 选择下载你需要的词向量,比如说GloVe.6B,它包含了600000个词汇的向量,每个向量的维度为300。下载完成后,将解压后的文件保存为.vec格式即可。以下是一个示例代码: ``` python import urllib.request # 下载GloVe训练词向量 url = 'http://nlp.stanford.edu/data/glove.6B.zip' urllib.request.urlretrieve(url, 'glove.6B.zip') # 解压文件 import zipfile with zipfile.ZipFile('glove.6B.zip', 'r') as zip_ref: zip_ref.extractall('glove.6B') # 将词向量保存为.vec文件 import os import numpy as np def save_word_vectors_to_file(file_path, word_vectors): with open(file_path, 'w', encoding='utf-8') as f_out: for word, vector in word_vectors.items(): vector_str = ' '.join([str(val) for val in vector]) f_out.write(f"{word} {vector_str}\n") def load_word_vectors_from_file(file_path): word_vectors = {} with open(file_path, 'r', encoding='utf-8') as f_in: for line in f_in: parts = line.strip().split() word = parts[0] vector = np.array([float(val) for val in parts[1:]]) word_vectors[word] = vector return word_vectors glove_file = 'glove.6B/glove.6B.300d.txt' word_vectors = load_word_vectors_from_file(glove_file) save_word_vectors_to_file('glove.6B/glove.6B.300d.vec', word_vectors) ``` 这个代码会从Stanford NLP Group的网站下载GloVe.6B预训练词向量,解压文件,然后保存为.vec格式。你可以更改文件路径和下载的词向量类型来适应你的需要。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值