1、安装gensim

!!!注意
我的环境中,使用pip安装gensim会更改numpy版本,导致tensorflow崩溃,我使用的是conda安装成功的。

# 我推荐
conda install -c conda-forge gensim
# 第二种,可能会更改你的别的模块版本,自测
pip install --upgrade gensim

2、代码

from gensim.models import Word2Vec, word2vec
from gensim.models.keyedvectors import KeyedVectors
from gensim.test.utils import datapath
from gensim import utils


class MyCorpus:
    def __iter__(self):
        # 这个方法会打开这个语料库,并将文件中的每一行转换为小写字母,然后返回一个生成器对象,这个生成器对象可以用于的带语料库中的每一个单词。
        corpus_path = datapath(r'pku_training.utf8')
        for line in open(corpus_path, encoding='utf-8'):
            yield utils.simple_preprocess(line)


if __name__ == '__main__':
    '''训练和保存'''
    sentences = MyCorpus()
    # sentence是一个可迭代对象
    # vector_size是我们指定的词向量维度
    # window制定了我们在训练过程中的窗口大小
    # sg指定了我们使用的算法:sg=0则使用CBOW算法,sg=1则使用了skip-gram算法
    # hs这个参数指定了我们使用的层次softmax算法,如果为hs=0,则使用负采样算法,如果hs=1则使用层次softmax算法
    model = Word2Vec(sentences=sentences, vector_size=200, window=7, sg=0, hs=1)

    # binary: 决定了是否以二进制的格式保存
    # 第一个为保存为二进制文件里,第二个为保存在txt文件里
    model.wv.save_word2vec_format(r'路径', binary=True)
    model.wv.save_word2vec_format(r'路径', binary=False)

    # 加载存盘大的词汇量模型
    word_vectors = KeyedVectors.load_word2vec_format(r'路径', binary=True)

    print('词汇数量:', len(word_vectors.key_to_index))
    print('词汇相似度:', word_vectors.similarity('抓住', '机遇'))
    print('获取到最近似的词汇:', word_vectors.most_similar('机遇', topn=2))

    # 使用most_similar接口进行词语的类比推理
    # 这里推理father-mother = 什么-woman
    # positive: 我们要找到的词汇与positive的词汇相似
    # negative: 我们要找到的词汇与negative不想似
    # topn: 我们要找到的词汇个数
    print('', word_vectors.most_similar(positive=['抓住'], negative=['新闻'], topn=2))

结果截图
在这里插入图片描述
语料资源已上传

更多推荐