【NLP】如何实现快速加载gensim word2vec的预训练的词向量模型

1 问题

通过以下代码,实现加载word2vec词向量,每次加载都是几分钟,效率特别低。

python 复制代码
from gensim.models import Word2Vec,KeyedVectors

# 读取中文词向量模型(需要提前下载对应的词向量模型文件)
word2vec_model = KeyedVectors.load_word2vec_format('hy-tmp/word2vec.bz2', binary=False)

2 解决方案

(1)方案一

第一次加载后保存为能够快速加载的文件,第二次加载就能快读读取。

python 复制代码
file_path = "word2vec/train_bio_word"
if os.path.exists(file_path):
    word2vec_model = KeyedVectors.load(file_path,mmap='r')
else:
    # 读取中文词向量模型(需要提前下载对应的词向量模型文件)
    word2vec_model = KeyedVectors.load_word2vec_format('hy-tmp/word2vec.bz2', binary=False)
    word2vec_model.init_sims(replace=True)
    word2vec_model.save(file_path)
    

(2)方案二

第一次加载后,只将使用到的词向量以表格的形式保存到本地,第二次读取就不需要加载全部word2vec的,只加载表格中的词向量。

python 复制代码
file_path = "word2vec/train_vocabulary_vector.csv"
if os.path.exists(file_path):
    # 读取词汇-向量字典,csv转字典
    vocabulary_vector = dict(pd.read_csv(file_path))
    # 此时需要将字典中的词向量np.array型数据还原为原始类型,方便以后使用
    for key,value in vocabulary_vector.items():
       vocabulary_vector[key] = np.array(value)
    
else:
    # 所有文本构建词汇表,words_cut 为分词后的list,每个元素为以空格分隔的str.
    vocabulary = list(set([word for item in text_data1 for word in item]))
    # 构建词汇-向量字典
    vocabulary_vector = {}
    for word in vocabulary:
       if word in word2vec_model:
          vocabulary_vector[word] = word2vec_model[word]
    # 储存词汇-向量字典,由于json文件不能很好的保存numpy词向量,故使用csv保存
    pd.DataFrame(vocabulary_vector).to_csv(file_path)

(3)方案三

不使用word2vec的原训练权重,使用Embedding工具库。自动下载权重文件后,高效使用。

参考:https://github.com/vzhong/embeddings

安装库

text 复制代码
pip install embeddings  # from pypi
pip install git+https://github.com/vzhong/embeddings.git  # from github
python 复制代码
from embeddings import GloveEmbedding, FastTextEmbedding, KazumaCharEmbedding, ConcatEmbedding

g = GloveEmbedding('common_crawl_840', d_emb=300, show_progress=True)
f = FastTextEmbedding()
k = KazumaCharEmbedding()
c = ConcatEmbedding([g, f, k])
for w in ['canada', 'vancouver', 'toronto']:
    print('embedding {}'.format(w))
    print(g.emb(w))
    print(f.emb(w))
    print(k.emb(w))
    print(c.emb(w))
相关推荐
小陈phd2 天前
大语言模型实战(十四)——MCP Prompts提示系统深度解析:构建智能提示模板库与LLM集成方案
人工智能·语言模型·自然语言处理
思通数科x2 天前
传统监控事后难追责?AI 违规识别智能系统让响应时间缩短
图像处理·人工智能·深度学习·目标检测·机器学习·计算机视觉·自然语言处理
小陈phd2 天前
大语言模型实战(十三)——MCP工具系统完全指南:从零构建AI可调用的工具生态(FastMCP+LLM工具调用循环)
人工智能·语言模型·自然语言处理
郝学胜-神的一滴2 天前
文海撷英,数林建模:词袋模型之奥义与中文处理实践
人工智能·python·程序人生·ai·自然语言处理·scikit-learn
Francek Chen2 天前
【自然语言处理】应用05:自然语言推断:使用注意力
人工智能·pytorch·深度学习·神经网络·自然语言处理
小陈phd2 天前
大语言模型实战(十五)——MCP Sampling采样请求完全解析:LLM参数微调与人工干预的完美融合
人工智能·语言模型·自然语言处理
natide2 天前
图结构差异-1-邻域重叠率(Neighborhood Overlap)
人工智能·深度学习·机器学习·自然语言处理·nlp
のハス2 天前
Chapter 3: 大语言模型基础 Part 1:从 N-gram 到词嵌入
人工智能·语言模型·自然语言处理·llm·agent
不错就是对2 天前
【agent-lightning】 - 2_使用 Agent-lightning 训练第一个智能体
人工智能·深度学习·神经网络·自然语言处理·chatgpt·transformer·vllm
imbackneverdie2 天前
从零到一,如何用AI高效构建国自然申请书初稿?
人工智能·自然语言处理·aigc·科研·ai写作·学术·国家自然科学基金