当前位置:   article > 正文

python 环境下gensim中的word2vec的使用笔记_train word2vec from scratch on the text8 corpus

train word2vec from scratch on the text8 corpus

centos 7, python2.7, gensim (0.13.1)

语料:

http://211.136.8.18/files/10940000015A9F94/mattmahoney.net/dc/text8.zip

程序:

# -*- coding: utf-8 -*-
'''
Created on 2016年8月29日
测试gensim使用
@author: root
'''

from gensim.models import word2vec
import logging
import numpy as np
# 主程序
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.Text8Corpus(u"/media/sf_workspace/nlp-workspace/nltk-test/word2vec/data/text8")  # 加载语料
n_dim=200
model = word2vec.Word2Vec(sentences, size=n_dim)  # 训练skip-gram模型; 默认window=5
# n_dim = 300
# #Initialize model and build vocab
# imdb_w2v = Word2Vec(size=n_dim, min_count=1)
# imdb_w2v.build_vocab(sentences)

# #Train the model over train_reviews (this may take several minutes)
# imdb_w2v.train(sentences)
# obtain the word vectors as follows:
text=["hi","no"]
vec = np.zeros(n_dim).reshape((1, n_dim))
print type(vec)
count = 0.
for word in text:
    try:
        vec += model[word].reshape((1, n_dim))
        print vec
        count += 1.
    except KeyError:
        continue
if count != 0:
    vec /= count
print count
print vec


# 计算两个词的相似度/相关程度
y1 = model.similarity("woman", "man")
print u"woman和man的相似度为:", y1
print "--------\n"

# 计算某个词的相关词列表
y2 = model.most_similar("good", topn=20)  # 20个最相关的
print u"和good最相关的词有:\n"
for item in y2:
    print item[0], item[1]
print "--------\n"

# 寻找对应关系
print ' "boy" is to "father" as "girl" is to ...? \n'
y3 = model.most_similar(['girl', 'father'], ['boy'], topn=3)
for item in y3:
    print item[0], item[1]
print "--------\n"

more_examples = ["he his she", "big bigger bad", "going went being"]
for example in more_examples:
    a, b, x = example.split()
    predicted = model.most_similar([x, b], [a])[0][0]
    print "'%s' is to '%s' as '%s' is to '%s'" % (a, b, x, predicted)
print "--------\n"

# 寻找不合群的词
y4 = model.doesnt_match("breakfast cereal dinner lunch".split())
print u"不合群的词:", y4
print "--------\n"

# 保存模型,以便重用
model.save("text8.model")
# 对应的加载方式
# model_2 = word2vec.Word2Vec.load("text8.model")

# 以一种C语言可以解析的形式存储词向量
model.save_word2vec_format("text8.model.bin", binary=True)
# 对应的加载方式
# model_3 = word2vec.Word2Vec.load_word2vec_format("text8.model.bin", binary=True)

if __name__ == "__main__":
    pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

中文

语料格式示例:

一一
一一列举
一一对应 一丁点 一丁点儿 一万年
一丈红
一下
一下子
一不做
一不小心
一专多能
一世
一丘之貉
一业
一丛
一丝一毫
一丝不挂
一丝不苟
一个
一个劲
一个样
一中
一中一台
一中全会
一举
一举一动
一举两得
一举多得

# -*- coding: utf-8 -*-
'''
Created on 2016年8月29日
测试gensim使用,处理中文语料
@author: root
'''

from gensim.models import word2vec
import logging
import sys
reload(sys) #重新载入sys
sys.setdefaultencoding("utf8") #设置默认编码格式
# 主程序
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.Text8Corpus(u"/media/sf_workspace/nlp-workspace/nltk-test/word2vec/data/test1.txt")  # 加载语料
model = word2vec.Word2Vec(sentences,min_count=1, size=200)  # 训练skip-gram模型

# 计算两个词的相似度/相关程度
y1 = model.similarity(u"淮南子", u"淮南子")
print  y1
print "--------\n"

# 计算某个词的相关词列表
y2 = model.most_similar(u"淮南子", topn=20)  # 20个最相关的
for item in y2:
    print item[0], item[1]
print "--------\n"

# 寻找对应关系
print u"书-不错,质量-"
y3 = model.most_similar([u'质量', u'不错'], [u'书'], topn=3)
for item in y3:
    print item[0], item[1]
print "--------\n"

# 寻找不合群的词
y4 = model.doesnt_match(u"书 书籍 教材 很".split())
print u"不合群的词:", y4
print "--------\n"

# 保存模型,以便重用
model.save(u"书评.model")
# 对应的加载方式
# model_2 = word2vec.Word2Vec.load("text8.model")

# 以一种C语言可以解析的形式存储词向量
model.save_word2vec_format(u"书评.model.bin", binary=True)
# 对应的加载方式
# model_3 = word2vec.Word2Vec.load_word2vec_format("text8.model.bin", binary=True)

# if __name__ == "__main__":
#     pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

参考:

https://districtdatalabs.silvrback.com/modern-methods-for-sentiment-analysis

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号