visio网站开发流程图,免费网站空间,网站开发经验与教训范文,移动互联网应用程序管理情况1 问题
通过以下代码#xff0c;实现加载word2vec词向量#xff0c;每次加载都是几分钟#xff0c;效率特别低。
from gensim.models import Word2Vec,KeyedVectors# 读取中文词向量模型#xff08;需要提前下载对应的词向量模型文件#xff09;
word2vec_model KeyedV…1 问题
通过以下代码实现加载word2vec词向量每次加载都是几分钟效率特别低。
from gensim.models import Word2Vec,KeyedVectors# 读取中文词向量模型需要提前下载对应的词向量模型文件
word2vec_model KeyedVectors.load_word2vec_format(hy-tmp/word2vec.bz2, binaryFalse)2 解决方案
1方案一 第一次加载后保存为能够快速加载的文件第二次加载就能快读读取。
file_path word2vec/train_bio_word
if os.path.exists(file_path):word2vec_model KeyedVectors.load(file_path,mmapr)
else:# 读取中文词向量模型需要提前下载对应的词向量模型文件word2vec_model KeyedVectors.load_word2vec_format(hy-tmp/word2vec.bz2, binaryFalse)word2vec_model.init_sims(replaceTrue)word2vec_model.save(file_path)
2方案二 第一次加载后只将使用到的词向量以表格的形式保存到本地第二次读取就不需要加载全部word2vec的只加载表格中的词向量。
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 安装库
pip install embeddings # from pypi
pip install githttps://github.com/vzhong/embeddings.git # from githubfrom embeddings import GloveEmbedding, FastTextEmbedding, KazumaCharEmbedding, ConcatEmbeddingg GloveEmbedding(common_crawl_840, d_emb300, show_progressTrue)
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))