您的位置:首页 > 其它

词向量 简单应用

2018-02-05 19:13 141 查看
词向量是一个比较好的东西,具体是什么原理在此就不讲了,我也说不清楚…但是使用的时候还是比较直观的。用的是python中的gensim库,其中有word2vec库可以使用。

词向量将词向量化,可以直观的算出两个词的“相关程度”,在大量的信息中抽取相关度较高的内容。直接上代码吧,代码很直观!

#_*_ coding:utf-8 _*_
from gensim.models import word2vec
from gensim.models import KeyedVectors
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.Text8Corpus("E:\\大数据\\词向量\\词向量语料\\text8")  # 加载语料
model = word2vec.Word2Vec(sentences, size=200)  # 训练skip-gram模型; 默认window=5

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

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

# 寻找对应关系
print ' "boy" is to "girl" as "man" is to ...? \n'
y3 = model.most_similar(['girl', 'man'], ['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 "不合群的词:", y4
print "--------\n"

'''
#但是不知道为什么我一直失败...
# 保存模型,以便重用
model.save(u"text8.model")
# 加载模型
# model_2 = word2vec.Word2Vec.load("text8.model")
'''

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




注意到了,中间注释了一段,原文中说这个是可以成功的,但是我就一直报错,所以用了另一种方法存储,在下一次就不用再训练模型了…emmm

上面的语料下载可以看http://mattmahoney.net/dc/text8.zip

简单了解一下词向量http://licstar.net/archives/328

深入了解词向量就得好好研究一下了。可以看看,我看不太懂。。。

http://blog.csdn.net/itplus/article/details/37969519

分词的话可以用结巴分词,比较好用,可以参考我之前的文章。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: