2021-07-13

python gensim 用word2vec处理英语语料

原文是2016年的,也没看到更新,自己用的时候发现有些函数变了位置,参数也跟以前不同了,这篇文章希望能给同为新手的你提供一点点帮助
原文链接:2016年的原文

练手三部曲之一二

word2vec理论没有什么过不过时的,就不废话了,自己查去吧。
看完理论后,结合 《基于深度学习的自然语言处理》这本书,给自己出了三个练手题
1、简单的wtv使用
2、用wtv处理中篇英语语料 语料地址:http://mattmahoney.net/dc/text8.zip
3、用wtv处理中篇中文语料
本篇内容围绕练习2

原文代码更正

1、

from gensim.models import word2vec #这是个模块
from gensim.models import Word2Vec #这是个函数

2、Word2Vec参数改变
原文:

model = word2vec.Word2Vec(sentences, size=200)  # 训练skip-gram模型; 默认window=5

gensim 4.0设置词嵌入维度变为 vector_size=

model = Word2Vec(sentences,window=5,vector_size=200)

3、词相关度函数位置改变
原文:

y1 = model.similarity("woman", "man")
# 计算某个词的相关词列表
y2 = model.most_similar("good", topn=20)  # 20个最相关的

现在:

y1 = model.wv.similarity("woman","man")#移入到wv中了
model.wv.most_similar(positive="man",topn=6)#与某词最相似的6个词

4、寻找不合群词函数位置改变
原文:

# 寻找不合群的词
y4 = model.doesnt_match("breakfast cereal dinner lunch".split())

现在:

#寻找不合群的词
y3= model.wv.doesnt_match("breakfast cereal dinner lunch".split())
print("这个句子中不合群的词是",y3)

全代码

from gensim.models import Word2Vec
from gensim.models import word2vec
import logging
from nltk import word_tokenize
#下面这句话查了以下说是日志,但也不知道有什么用
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
#加载语料
sentences = word2vec.Text8Corpus(u"F:\\nlp_resource\\text8\\text8")
model = Word2Vec(sentences,window=5,vector_size=200)
#看下一个词的词向量
print(len(model.wv['man']))
print('------')
print(model.wv['man'])

y1 = model.wv.similarity("woman","man")
print("woman和man的相似度为:",y1)#某两个词的相似度

model.wv.most_similar(positive="man",topn=6)#与某词最相似的6个词
words=list(model.wv.key_to_index)
print("该语料总长度:",len(words))

model.wv.most_similar(positive="american",topn=6)
#寻找对应关系
y2 = model.wv.most_similar(['girl','father'],['boy'],topn=3)
print("boy与father之间的关系类似于,girl和",y2)

#寻找不合群的词
y3= model.wv.doesnt_match("breakfast cereal dinner lunch".split())
print("这个句子中不合群的词是",y3)

输出结果

用的jupyter notebook,截图好麻烦,所以就不放了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值