相关推荐:
【自然语言处理】【Word2Vec(一)】Word2Vec之前的词表示和文本表示:one-hot_bag of words_TF-IDF_n-gram_Cocurrence matrix和NNLM
【自然语言处理】【Word2Vec(二)】超详细的原理推导(包含负采样和层次softmax)
import pandas as pdimport numpy as npimport jiebafrom gensim.models import word2vec
一、加载数据
document = pd.read_csv("./Data/BYX.txt",encoding="GBK",header=None)document.columns = ['sentences'] # 重命名列名document['sentences'] = document['sentences'].apply(lambda x: x.strip()) # 去除文本前后的空白document['lens'] = document['sentences'].apply(len) # 统计文本长度document = document[document['lens']>1] # 去除文本长度小于等于1的文本document.index = np.arange(len(document))
二、去除特殊字符
当然也可以不做特殊字符处理
punct = "/-'?!.,#$%\'()*+-/:;<=>@[\\]^_`{|}~`" + '""“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\×™√²—–&'def clean_special_chars(text, punct):for p in punct:text = text.replace(p, ' ')return textdocument['sentences'] = document['sentences'].apply(lambda x:clean_special_chars(x,punct))
三、分词
jieba.suggest_freq('桐原亮司',True)jieba.suggest_freq('桐原洋介',True)jieba.suggest_freq('笹垣润三',True)jieba.suggest_freq('桐原弥生子',True)jieba.suggest_freq('唐泽雪穗',True)jieba.suggest_freq('雪穗',True)jieba.suggest_freq('唐泽礼子',True)jieba.suggest_freq('园村友彦',True)jieba.suggest_freq('松浦勇',True)jieba.suggest_freq('寺崎忠夫',True)jieba.suggest_freq('田川敏夫',True)jieba.suggest_freq('秋吉雄一',True)jieba.suggest_freq('西口奈美江',True)
1
document['sentences'] = document['sentences'].apply(lambda x: ' '.join(jieba.cut(x)))
四、gensim和word2vec介绍
gensim是一个NLP的工具,其中关于word2vec的工具均在gensim.models.word2vec下。和算法有关的参数都在类gensim.models.word2vec.Word2Vec中。
sentences:我们要分析的语料,可以是一个列表,或者从文件中遍历读出。
size: 词向量的维度,默认值是100。如果语料库较大则应该将该值调大。
window:即词向量上下文最大距离,这个参数在我们的算法原理篇中标记为c,window越大,则和某一词较远的词也会产生上下文关系。默认值为5。
sg: 即我们的word2vec两个模型的选择了。如果是0, 则是CBOW模型,是1则是Skip-Gram模型,默认是0即CBOW模型。
hs: 即我们的word2vec两个解法的选择了,如果是0, 则是Negative Sampling,是1的话并且负采样个数negative大于0, 则是Hierarchical Softmax。默认是0即Negative Sampling。
negative:即使用Negative Sampling时负采样的个数,默认是5。推荐在[3,10]之间。这个参数在我们的算法原理篇中标记为neg。
min_count:需要计算词向量的最小词频。这个值可以去掉一些很生僻的低频词,默认是5。如果是小语料,可以调低这个值。
五、训练模型
sentences = [sentence.split() for sentence in document['sentences']]
model = word2vec.Word2Vec(size=20,window=3)model.build_vocab(sentences)model.train(sentences,total_examples=model.corpus_count,epochs=model.epochs*3)
(1705861, 2744595)
六、保存模型与加载模型
model.save('./mymodel') # 模型保存
model = word2vec.Word2Vec.load('./mymodel') # 加载模型,还可以train()函数继续训练
model.wv.save_word2vec_format('./word2vec.txt',binary=False) # 仅保存词向量,不保存模型
七、词向量的使用
1.获得某个词的词向量
model['警察']
array([ 0.5641069 , 0.20711453, 1.2791238 , -0.46662605, 0.15338947,-0.8355605 , -0.31797206, 0.19973843, 0.7164703 , -0.136376 ,1.793 , 0.7504985 , 0.16553111, -0.14321175, 0.88424015,0.27199823, -0.22283189, 0.24914157, 0.6664467 , -0.6253866 ],dtype=float32)
2.计算近似词
model.wv.most_similar(['警察'],topn=5)
[('康晴', 0.8587027788162231),('老师', 0.8538543581962585),('菊池', 0.8275039196014404),('田川', 0.8126981258392334),('无聊', 0.7966194748878479)]
3.计算两个词之间的相似度
model.wv.similarity('雪穗','美佳')
0.8242445