赞
踩
Gensim(http://pypi.python.org/pypi/gensim)是一款开源的第三方Python工具包,用于从原始的非结构化的文本中,无监督地学习到文本隐层的主题向量表达。 主要用于主题建模和文档相似性处理,它支持包括TF-IDF,LSA,LDA,和word2vec在内的多种主题模型算法。Gensim在诸如获取单词的词向量等任务中非常有用。
使用Gensim训练Word2vec十分方便,训练步骤如下:
1)将语料库预处理:一行一个文档或句子,将文档或句子分词(以空格分割,英文可以不用分词,英文单词之间已经由空格分割,中文预料需要使用分词工具进行分词,常见的分词工具有StandNLP、ICTCLAS、Ansj、FudanNLP、HanLP、结巴分词等);
2)将原始的训练语料转化成一个sentence的迭代器,每一次迭代返回的sentence是一个word(utf8格式)的列表。可以使用Gensim中word2vec.py中的LineSentence()方法实现;
3)将上面处理的结果输入Gensim内建的word2vec对象进行训练即可:
- from gensim.models import Word2Vec
-
- sentences = word2vec.LineSentence('./in_the_name_of_people_segment.txt')
- # in_the_name_of_people_segment.txt 分词之后的文档
-
- model = Word2Vec(sentences , size=100, window=5, min_count=1, workers=4)
在gensim中,word2vec 相关的API都在包gensim.models.word2vec中。和算法有关的参数都在类gensim.models.word2vec. Word2Vec中。算法需要注意的参数有:
- class Word2Vec(utils.SaveLoad):
- def __init__(
- self, sentences=None, size=100, alpha=0.025, window=5, min_count=5,
- max_vocab_size=None, sample=1e-3, seed=1, workers=3, min_alpha=0.0001,
- sg=0, hs=0, negative=5, cbow_mean=1, hashfxn=hash, iter=5, null_word=0,
- trim_rule=None, sorted_vocab=1, batch_words=MAX_WORDS_IN_BATCH):
- import os
- import numpy as np
- import nltk
- import datetime as dt
- from keras.models import Sequential, load_model
- from keras.layers import Dense
- from keras.layers import Dropout
- from keras.layers import LSTM
- from gensim.models import Word2Vec
-
-
- # 1.文本读入
- # (1)加载文本
- raw_text = ''
- # os.listdir()方法用于返回指定的文件夹包含的文件或文件夹的名字的列表
- for file in os.listdir('./input/'):
- if file.endswith(".txt"):
- raw_text += open("./input/" + file, errors='ignore').read() + '\n\n'
- raw_text = raw_text.lower()
-
- # (2)加载punkt句子分割器
- sentensor = nltk.data.load('tokenizers/punkt/english.pickle')
- # <nltk.tokenize.punkt.PunktSentenceTokenizer at 0x16cc42020f0>
-
- # (3)对句子进行分割:将文章分割为句子列表
- sents = sentensor.tokenize(raw_text) # 句子列表['句子1.','句子2.'...]
- corpus = []
-
- # (4)分词word tokenize:将句子分割为单词列表
- for sen in sents:
- corpus.append(nltk.word_tokenize(sen))
- # 单词列表[['sexes', 'similar', '.'],['family', 'hirundinidae', '.'],...]
-
- # 2.构建词向量:W2V
- w2v_model = Word2Vec(corpus, size=128, window=5, min_count=3, workers=4) # 128维的词向量
-
- # 3. 处理我们的training data,把源数据变成一个长长的x,好让LSTM学会predict下一个单词
- raw_input = [item for sublist in corpus for item in sublist]
- # 将corpus的二维变为一维['sexes', 'similar', '.','family', 'hirundinidae', '.',...]
-
- text_stream = []
-
- vocab = w2v_model.wv.vocab # 字典dict:获取词向量中每个单词
- '''
- {'project': <gensim.models.keyedvectors.Vocab at 0x1be2f656048>,
- 'gutenberg': <gensim.models.keyedvectors.Vocab at 0x1be2f656080>,
- "'s": <gensim.models.keyedvectors.Vocab at 0x1be2f6560b8>,...}
- '''
-
- # 将raw_input中在w2v_model词向量中的单词添加到text_stream
- for word in raw_input:
- if word in vocab:
- text_stream.append(word)
-
- # 4. 构造训练测试集:窗口化,处理成LSTM的输入格式
- seq_length = 10
- x = []
- y = []
- for i in range(0, len(text_stream) - seq_length):
- given = text_stream[i:i + seq_length]
- predict = text_stream[i + seq_length]
- x.append(np.array([w2v_model[word] for word in given])) # 将每个单词转换为词向量
- y.append(w2v_model[predict])
-
- # len(w2v_model[given[0]])=128 w2v_model[word]为word对应的词向量
-
- # 5. ①将input的数字表达(w2v),变成LSTM需要的数组格式: [样本数,时间步伐,特征],
- # ②对于output,我们直接用128维的输出
- x = np.reshape(x, (-1, seq_length, 128))
- y = np.reshape(y, (-1, 128))
-
- # 6. LSTM模型构建
- model = Sequential()
- model.add(LSTM(256, dropout_W=0.2, dropout_U=0.2, input_shape=(seq_length,128)))
- model.add(Dropout(0.2))
- model.add(Dense(128, activation='sigmoid'))
- model.compile(loss='mse', optimizer='adam')
-
- # 7.跑模型
- model.fit(x, y, nb_epoch=30, batch_size=2048)
- save_fname = os.path.join('./', '%s-e%s-3.h5' % (dt.datetime.now().strftime('%Y%m%d-%H%M%S'),str(50)))
- model.save(save_fname)
-
- # 8. 测试
- # ①
- def predict_next(input_array):
- x = np.reshape(input_array, (-1, seq_length, 128))
- y = model.predict(x)
- return y
-
- def string_to_index(raw_input):
- raw_input = raw_input.lower()
- input_stream = nltk.word_tokenize(raw_input)
- res = []
- for word in input_stream[(len(input_stream)-seq_length):]:
- res.append(w2v_model[word])
- return res
-
- def y_to_word(y):
- word = w2v_model.most_similar(positive=y, topn=1) # 获取单个词相关的前n个词语
- return word
- # ②
- def generate_article(init, rounds=30):
- in_string = init.lower()
- for i in range(rounds):
- n = y_to_word(predict_next(string_to_index(in_string)))
- in_string += ' ' + n[0][0]
- # print('n[0]:', n[0]) = ('curiosity', 0.7301754951477051)
- print('n[0][0]:', n[0][0])
- return in_string
-
- # ③
- # init = 'Language Models allow us to measure how likely is, which is an important for Machine'
- init1 = 'As I went in to see the famous Booth Collection, a thought of the bird I have just described came into my'
- article1 = generate_article(init1)

在gensim 1.0.0 以前的版本可以使用:model.vocab
在 gensim 1.0以后的版本使用:model.wv.vocab
选择的《人民的名义》的小说原文作为语料,语料原文在这里。
完整代码参见:github: https://github.com/ljpzzz/machinelearning/blob/master/natural-language-processing/word2vec.ipynb
拿到了原文,我们首先要进行分词,这里使用结巴分词完成。在中文文本挖掘预处理流程总结中,我们已经对分词的原理和实践做了总结。因此,这里直接给出分词的代码,分词的结果,我们放到另一个文件中。代码如下, 加入下面的一串人名是为了结巴分词能更准确的把人名分出来。
- # -*- coding: utf-8 -*-
-
- import jieba
- import jieba.analyse
-
- 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)
- 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)
-
- with open('./in_the_name_of_people.txt') as f:
- document = f.read()
-
- #document_decode = document.decode('GBK')
-
- document_cut = jieba.cut(document)
- #print ' '.join(jieba_cut) //如果打印结果,则分词效果消失,后面的result无法显示
- result = ' '.join(document_cut)
- result = result.encode('utf-8')
- with open('./in_the_name_of_people_segment.txt', 'w') as f2:
- f2.write(result)

拿到了分词后的文件,在一般的NLP处理中,会需要去停用词。由于word2vec的算法依赖于上下文,而上下文有可能就是停词。因此对于word2vec,我们可以不用去停词。
现在我们可以直接读分词后的文件到内存。这里使用了word2vec提供的LineSentence类来读文件,然后套用word2vec的模型。这里只是一个示例,因此省去了调参的步骤,实际使用的时候,你可能需要对我们上面提到一些参数进行调参。
- # import modules & set up logging
- import logging
- import os
- from gensim.models import word2vec
-
- logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
-
- sentences = word2vec.LineSentence('./in_the_name_of_people_segment.txt')
-
- model = word2vec.Word2Vec(sentences, hs=1,min_count=1,window=3,size=100)
模型出来了,我们可以用来做什么呢?这里给出三个常用的应用。
代码如下:
- req_count = 5
- for key in model.wv.similar_by_word('沙瑞金'.decode('utf-8'), topn =100):
- if len(key[0])==3:
- req_count -= 1
- print key[0], key[1]
- if req_count == 0:
- break;
我们看看沙书记最相近的一些3个字的词(主要是人名)如下:
- 高育良 0.967257142067
- 李达康 0.959131598473
- 田国富 0.953414440155
- 易学习 0.943500876427
- 祁同伟 0.942932963371
这里给出了书中两组人的相似程度:
- print model.wv.similarity('沙瑞金'.decode('utf-8'), '高育良'.decode('utf-8'))
- print model.wv.similarity('李达康'.decode('utf-8'), '王大路'.decode('utf-8'))
输出如下:
- 0.961137455325
- 0.935589365706
这里给出了人物分类题:
print model.wv.doesnt_match(u"沙瑞金 高育良 李达康 刘庆祝".split())
word2vec也完成的很好,输出为"刘庆祝"。
以上就是用gensim学习word2vec实战的所有内容。
https://blog.csdn.net/sinat_26917383/article/details/69803018#800_420
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。