1 問(wèn)題
通過(guò)以下代碼,實(shí)現(xiàn)加載word2vec詞向量,每次加載都是幾分鐘,效率特別低。
from gensim.models import Word2Vec,KeyedVectors
# 讀取中文詞向量模型(需要提前下載對(duì)應(yīng)的詞向量模型文件)
word2vec_model = KeyedVectors.load_word2vec_format('hy-tmp/word2vec.bz2', binary=False)
2 解決方案
(1)方案一
第一次加載后保存為能夠快速加載的文件,第二次加載就能快讀讀取。
file_path = "word2vec/train_bio_word"
if os.path.exists(file_path):
word2vec_model = KeyedVectors.load(file_path,mmap='r')
else:
# 讀取中文詞向量模型(需要提前下載對(duì)應(yīng)的詞向量模型文件)
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的,只加載表格中的詞向量。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-839720.html
file_path = "word2vec/train_vocabulary_vector.csv"
if os.path.exists(file_path):
# 讀取詞匯-向量字典,csv轉(zhuǎn)字典
vocabulary_vector = dict(pd.read_csv(file_path))
# 此時(shí)需要將字典中的詞向量np.array型數(shù)據(jù)還原為原始類型,方便以后使用
for key,value in vocabulary_vector.items():
vocabulary_vector[key] = np.array(value)
else:
# 所有文本構(gòu)建詞匯表,words_cut 為分詞后的list,每個(gè)元素為以空格分隔的str.
vocabulary = list(set([word for item in text_data1 for word in item]))
# 構(gòu)建詞匯-向量字典
vocabulary_vector = {}
for word in vocabulary:
if word in word2vec_model:
vocabulary_vector[word] = word2vec_model[word]
# 儲(chǔ)存詞匯-向量字典,由于json文件不能很好的保存numpy詞向量,故使用csv保存
pd.DataFrame(vocabulary_vector).to_csv(file_path)
(3)方案三
不使用word2vec的原訓(xùn)練權(quán)重,使用Embedding工具庫(kù)。自動(dòng)下載權(quán)重文件后,高效使用。
參考:https://github.com/vzhong/embeddings
安裝庫(kù)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-839720.html
pip install embeddings # from pypi
pip install git+https://github.com/vzhong/embeddings.git # from github
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))
到了這里,關(guān)于【NLP】如何實(shí)現(xiàn)快速加載gensim word2vec的預(yù)訓(xùn)練的詞向量模型的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!