一、 準備環(huán)境和語料:
- 新聞20w+篇(格式:
標題
。正文
)
【新聞可以自己從各大新聞網(wǎng)站爬取,也可以下載開源的新聞數(shù)據(jù)集,如
二、分詞
先對新聞文本進行分詞,使用的是結(jié)巴分詞工具,將分詞后的文本保存在seg201708.txt
,以備后期使用。
安裝jieba工具包:pip install jieba
# -*- coding: utf-8 -*-
import jieba
import io
# 加載自己的自己的金融詞庫
jieba.load_userdict("financialWords.txt")
def main():
with io.open('news201708.txt','r',encoding='utf-8') as content:
for line in content:
seg_list = jieba.cut(line)
# print '/'.join(seg_list)
with io.open('seg201708.txt', 'a', encoding='utf-8') as output:
output.write(' '.join(seg_list))
if __name__ == '__main__':
main()
三、訓(xùn)練word2vec模型
使用python的gensim包進行訓(xùn)練。
安裝gemsim包:pip install gemsim
from gensim.models import word2vec
def main():
num_features = 300 # Word vector dimensionality
min_word_count = 10 # Minimum word count
num_workers = 16 # Number of threads to run in parallel
context = 10 # Context window size
downsampling = 1e-3 # Downsample setting for frequent words
sentences = word2vec.Text8Corpus("seg201708.txt")
model = word2vec.Word2Vec(sentences, workers=num_workers, \
size=num_features, min_count = min_word_count, \
window = context, sg = 1, sample = downsampling)
model.init_sims(replace=True)
# 保存模型,供日後使用
model.save("model201708")
# 可以在加載模型之后使用另外的句子來進一步訓(xùn)練模型
# model = gensim.models.Word2Vec.load('/tmp/mymodel')
# model.train(more_sentences)
if __name__ == "__main__":
main()
- 參數(shù)說明
- sentences:可以是一個·ist,對于大語料集,建議使用BrownCorpus,Text8Corpus或ineSentence構(gòu)建。
- sg: 用于設(shè)置訓(xùn)練算法,默認為0,對應(yīng)CBOW算法;sg=1則采用skip-gram算法。
- size:是指特征向量的維度,默認為100。大的size需要更多的訓(xùn)練數(shù)據(jù),但是效果會更好. 推薦值為幾十到幾百。
- window:表示當前詞與預(yù)測詞在一個句子中的最大距離是多少
- alpha: 是學(xué)習(xí)速率
- seed:用于隨機數(shù)發(fā)生器。與初始化詞向量有關(guān)。
- min_count: 可以對字典做截斷. 詞頻少于min_count次數(shù)的單詞會被丟棄掉, 默認值為5
- max_vocab_size: 設(shè)置詞向量構(gòu)建期間的RAM限制。如果所有獨立單詞個數(shù)超過這個,則就消除掉其中最不頻繁的一個。每一千萬個單詞需要大約1GB的RAM。設(shè)置成None則沒有限制。
- sample: 高頻詞匯的隨機降采樣的配置閾值,默認為1e-3,范圍是(0,1e-5)
- workers參數(shù)控制訓(xùn)練的并行數(shù)。
- hs: 如果為1則會采用hierarchica·softmax技巧。如果設(shè)置為0(defau·t),則negative sampling會被使用。
- negative: 如果>0,則會采用negativesamp·ing,用于設(shè)置多少個noise words
- cbow_mean: 如果為0,則采用上下文詞向量的和,如果為1(defau·t)則采用均值。只有使用CBOW的時候才起作用。
- hashfxn: hash函數(shù)來初始化權(quán)重。默認使用python的hash函數(shù)
- iter: 迭代次數(shù),默認為5
- trim_rule: 用于設(shè)置詞匯表的整理規(guī)則,指定那些單詞要留下,哪些要被刪除。可以設(shè)置為None(min_count會被使用)或者一個接受()并返回RU·E_DISCARD,uti·s.RU·E_KEEP或者uti·s.RU·E_DEFAU·T的
- sorted_vocab: 如果為1(defau·t),則在分配word index 的時候會先對單詞基于頻率降序排序。
- batch_words:每一批的傳遞給線程的單詞的數(shù)量,默認為10000
四、word2vec應(yīng)用
model = Word2Vec.load('model201708') #模型讀取方式
model.most_similar(positive=['woman', 'king'], negative=['man']) #根據(jù)給定的條件推斷相似詞
model.doesnt_match("breakfast cereal dinner lunch".split()) #尋找離群詞
model.similarity('woman', 'man') #計算兩個單詞的相似度
model['computer'] #獲取單詞的詞向量