この記事はWord2Vecは、中国語の単語ベクトルを訓練して、「単語ベクトル」() -捜索犬ニュースデータセットを使用する 2つのコーパスのマージに基づいて、その後、訓練を受け、より良い単語ベクトルモデル。
参考:中国語の単語のトレーニングコーパスベクトル使っ基づきword2vecウィキ
小さなプロジェクト(Gensimライブラリ) -ウィキペディア中国のデータ処理
ダウンロードデータセット
ダウンロードするにはここをクリックしてください:Wikiのコーパスは、日付を選択しました。
ファイルはzhwiki-最新ページ-articles.xml.bz2、サイズ1.75ギガバイト(特に低速ダウンロード速度)がダウンロードされます。
データ処理の設定
(A)テキスト抽出
圧縮されたファイルからテキストを抽出する方法は2つあります。
- 使用gensim.corporaのWikiCorpusを直接ウィキペディアコーパス処理に。保存wikiCorpus / wikiCorpus.txt
from gensim.corpora import WikiCorpus
if __name__ == '__main__':
print('主程序开始...')
input_file_name = 'zhwiki-latest-pages-articles.xml.bz2'
output_file_name = 'wikiCorpus/wikiCorpus.txt'
print('开始读入wiki数据...')
input_file = WikiCorpus(input_file_name, lemmatize=False, dictionary={})
print('wiki数据读入完成!')
print('处理程序开始...')
count = 0
with open(output_file_name, 'wb') as output_file:
for text in input_file.get_texts():
output_file.write(' '.join(text).encode("utf-8"))
output_file.write('\n'.encode("utf-8"))
count = count + 1
if count % 10000 == 0:
print('目前已处理%d条数据' % count)
print('处理程序结束!')
output_file.close()
print('主程序结束!')
- ダウンロードウィキペディアExtractorの抽出テキストを。
データ・セットの処理が完了し、合計35ワット+データの断片、以下の効果。私たちは、あまりにも好きではない、句読点が削除されたことが判明しました!!!
(B)の簡素化
ダウンロードopenccは、文字変換を行います。
wikiCorpus.txtフォルダにコピーし、使用インジケータCDをフォルダ入力にopencc -i wikiCorpus.txt -o wikiCorpusSim.txt -c t2s.json
変換を完了するためには、変換されwikiCorpusSim.txtがに保存されてPythonのプロジェクト示すように、結果を:
(C)ワード文書
その前にSogouのデータセットを行っている場合、このステップは非常に精通している必要があります。
import jieba
filePath = 'wikiCorpus/wikiCorpusSim.txt' # 简化后文本
fileSegWordDonePath = 'wikiCorpus/wikiCorpusSegDone.txt' # 分词处理后文本
# 将每一行文本依次存放到一个列表
fileTrainRead = []
with open(filePath, encoding='utf-8') as fileTrainRaw:
for line in fileTrainRaw:
fileTrainRead.append(line)
# 用jieba进行分词
fileTrainSeg = []
file_userDict = 'dict.txt' # 自定义的词典
jieba.load_userdict(file_userDict)
for i in range(len(fileTrainRead)):
fileTrainSeg.append([' '.join(jieba.cut(fileTrainRead[i], cut_all=False))])
if i % 100 == 0: # 每处理100个就打印一次
print(i)
# 处理后写入文件
with open(fileSegWordDonePath, 'wb') as fW:
for i in range(len(fileTrainSeg)):
fW.write(fileTrainSeg[i][0].encode('utf-8'))
fW.write('\n'.encode("utf-8"))
(D)データセットを組み合わせます
データ・セットとマージWikiを処理する前に、優れた検索犬、フライドチキン無敵の中国のコーパスを生成します。
filePath1 = 'wikiCorpus/wikiCorpusSegDone.txt' # wiki分词后语料库
filePath2 = 'sougouCorpus/sougouCorpusSegDone.txt' # 搜狗语料库
filePath3 = 'corpusFinal.txt' # 最终语料库
fileFinal = []
countS = 0 # sougou计数
countW = 0 # wiki计数
# 打开搜狗语料库
with open(filePath2, encoding='utf-8') as ff1:
print("---成功导入搜狗语料库---")
for line in ff1:
fileFinal.append(line)
countS = countS + 1
if countS % 10000 == 0:
print("---------已导入%d篇搜狗文章---------" % countS)
# 打开维基语料库
with open(filePath1, encoding='utf-8') as ff2:
print("---成功导入wiki语料库---")
for line in ff2:
fileFinal.append(line)
countW = countW + 1
if countW % 10000 == 0:
print("---------已导入%d篇维基文章---------" % countW)
# 打开最终文档,逐行写入
with open(filePath3, 'wb') as ff:
for i in range(len(fileFinal)):
ff.write(fileFinal[i].encode('utf-8'))
if i % 10000 == 0:
print("---------已合并%d篇文章---------" % i)
print("---------一共读入%d行---------" % len(fileFinal))
print("---------完成合并---------")
合計212ワット+(寄与するデータの行71ワット行+ Sogouの141ワットライン)
のサイズ3.35ギガバイト
トレーナー
または古いコードが使用されています
import logging
import sys
import gensim.models as word2vec
from gensim.models.word2vec import LineSentence, logger
# import smart_open
def train_word2vec(dataset_path, out_vector):
# 设置输出日志
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
logger.info("running %s" % ' '.join(sys.argv))
# 把语料变成句子集合
sentences = LineSentence(dataset_path)
# sentences = LineSentence(smart_open.open(dataset_path, encoding='utf-8')) # 或者用smart_open打开
# 训练word2vec模型(size为向量维度,window为词向量上下文最大距离,min_count需要计算词向量的最小词频)
model = word2vec.Word2Vec(sentences, size=128, sg=1, window=6, min_count=5, workers=4, iter=6)
# (iter随机梯度下降法中迭代的最大次数,sg为1是Skip-Gram模型)
# 保存word2vec模型
model.save("word2vec.model")
model.wv.save_word2vec_format(out_vector, binary=False)
# 加载模型
def load_word2vec_model(w2v_path):
model = word2vec.Word2Vec.load(w2v_path)
return model
# 计算词语最相似的词
def calculate_most_similar(self, word):
similar_words = self.wv.most_similar(word)
print(word)
for term in similar_words:
print(term[0], term[1])
# 计算两个词相似度
def calculate_words_similar(self, word1, word2):
print(self.wv.similarity(word1, word2))
# 找出不合群的词
def find_word_dismatch(self, list):
print(self.wv.doesnt_match(list))
if __name__ == '__main__':
dataset_path = 'corpusFinal.txt'
out_vector = 'corpusFinal.vector'
train_word2vec(dataset_path, out_vector) # 训练模型
# model = load_word2vec_model("word2vec.model") # 加载模型
# calculate_most_similar(model, "病毒") # 找相近词
# calculate_words_similar(model, "法律", "制度") # 两个词相似度
# print(model.wv.__getitem__('男人')) # 词向量
# list = ["早饭", "吃饭", "恰饭", "嘻哈"]
# find_word_dismatch(model, list)
言葉の「ウイルス」に関連付けられています:
参考記事
中国語の単語トレーニングコーパスのwikiベクトル使っ基づきword2vec
小さなプロジェクト(Gensimライブラリ) -ウィキペディア中国のデータ処理