Gensim Word2Vec model

本文介绍了Gensim的Word2Vec模型,包括词袋模型、Skip-gram和CBOW,提供了训练自定义模型的步骤,并讨论了训练参数如min_count和size。还涉及到模型评估、在线学习、训练损失计算以及如何提高模型性能的技巧。通过实例展示了Word2Vec在词汇相似性评估中的应用。
摘要由CSDN通过智能技术生成

Word2Vec model

import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

Bag of word

词袋模型,把每一个文本转化成一个固定长度的向量。

但是向量间的距离并不总是反映含义上的差距。

Inroduction of the word2vec model

word2vec demo

使用预训练模型进行演示。

import gensim.downloader as api
wv = api.load('word2vec-google-news-300')

从模型中抽取10个单词

for i, word in enumerate(wv.vocab):
    if i == 10:
        break
    print(word)

Out:

</s>
in
for
that
is
on
##
The
with
said

训练自己的模型

使用 Lee Corpus 进行训练,这里使用内存友好的方法演示:

from gensim.test.utils import datapath
from gensim import utils

class MyCorpus(object):
    """An interator that yields sentences (lists of str)."""

    def __iter__(self):
        corpus_path = datapath('lee_background.cor')
        for line in open(corpus_path):
            # assume there's one document per line, tokens separated by whitespace
            yield utils.simple_preprocess(line)

如果想自定义预处理方法,就可以直接在上面进行。

训练模型

import gensim.models

sentences = MyCorpus()
model = gensim.models.Word2Vec(sentences=sentences)

wv is ‘word vectors’

vec_king = model.wv['king']  # 得到king 的 vector

Retrieving the vocabulary works the same way:

for i, word in enumerate(model.wv.vocab):
    if i == 10:
        break
    print(word)

Out:

hundreds
of
people
have
been
forced
to
their
homes
in

保存模型

# 我觉得这样保存模型就行
model_save_name = 'gensim-model.gth'
model.save(model_save_name)

# 读取模型
new_model = gensim.models.Word2Vec.load(model_save_name)

You can store/load models using the standard gensim methods:

import tempfile

with tempfile.NamedTemporaryFile(prefix='gensim-model-', delete=False) as tmp:
    temporary_filepath = tmp.name
    model.save(temporary_filepath)
    #
    # The model is now safely stored in the filepath.
    # You can copy it to other machines, share it with others, etc.
    #
    # To load a saved model:
    #
    new_model = gensim.models.Word2Vec.load(temporary_filepath)

In addition, you can load models created by the original C tool, both using its text and binary formats:

model = gensim.models.KeyedVectors.load_word2vec_format('/tmp/vectors.txt', binary=False)
# using gzipped/bz2 input works too, no need to unzip
model = gensim.models.KeyedVectors.load_word2vec_format('/tmp/vectors.bin.gz', binary=True)

训练参数

https://blog.csdn.net/qq_42067550/article/details/106531036

  1. min_count

    词的最小出现次数。

min_count is for pruning the internal dictionary. Words that appear only once or twice in a billion-word corpus are probably uninteresting typos and garbage. In addition, there’s not enough data to make any meaningful training on those words, so it’s best to ignore them:

default value of min_count=5

model = gensim.models.Word2Vec(sentences, min_count=10)
  1. size

    把单词映射到几维空间。

size is the number of dimensions (N) of the N-dimensional space that gensim Word2Vec maps the words onto.

Bigger size values require more training data, but can lead to better (more accurate) models. Reasonable values are in the tens to hundreds.

# default value of size=100
model = gensim.models.Word2Vec(sentences, size=200)
  1. workers

    多线程。

workers , the last of the major parameters (full list here) is for training parallelization, to speed up training:

# default value of workers=3 (tutorial says 1...)
model = gensim.models.Word2Vec(sentences, workers=4)

评估

https://blog.csdn.net/qq_42067550/article/details/106553257

In the December 2016 release of Gensim we added a better way to evaluate semantic similarity.

By default it uses an academic dataset WS-353 but one can create a dataset specific to your business based on it. It contains word pairs together with human-assigned similarity judgments. It measures the relatedness or co-occurrence of two words. For example, ‘coast’ and ‘shore’ are very similar as they appear in the same context. At the same time ‘clothes’ and ‘closet’ are less similar because they are related but not interchangeable.

# Evaluation
model.wv.evaluate_word_pairs(datapath('wordsim353.tsv'))
((0.1952515342533469, 0.13490728041580877),
 SpearmanrResult(correlation=0.19127414318530173, pvalue=0.14319638687965558),
 83.0028328611898)

返回值:

  • pearson (tuple of (float, float)) – Pearson correlation coefficient with 2-tailed p-value.
    皮尔森相关系数(2 个双尾 p 值)
  • spearman (tuple of (float, float)) – Spearman rank-order correlation coefficient between the similarities from the dataset and the similarities produced by the model itself, with 2-tailed p-value.
    斯皮尔曼等级相关系数,针对数据集的相关性和模型产生的相关性,2 个 双尾 p 值。
  • oov_ratio (float) – The ratio of pairs with unknown words.
    配对中有未知单词的比例。

所以上面的结果显示,我们测试的成绩并不好呀,应该是训练语料较小的原因吧!

!!! 注意:

  • 在 Google 测试集和 WS-353 上取得好成绩并不意味着在应用中也会表现很好~
  • 反之亦然~
  • 最好直接在所需的任务中进行测试!比如我们要做一个分类任务,那直接看分类的效果就好了!

在线学习/ 继续学习(载入模型)

model = gensim.models.Word2Vec.load(temporary_filepath)
more_sentences = [
    ['Advanced', 'users', 'can', 'load', 'a', 'model',
     'and', 'continue', 'training', 'it', 'with', 'more', 'sentences']
]
model.build_vocab(more_sentences, update=True)
model.train(more_sentences, total_examples=model.corpus_count, epochs=model.iter)

# cleaning up temporary file
import os
os.remove(temporary_filepath)

model.train 方法参数如下:

train(sentences=None, corpus_file=None, total_examples=None, total_words=None, epochs=None, start_alpha=None, end_alpha=None, word_count=0, queue_factor=2, report_delay=1.0, compute_loss=False, callbacks=())

其中 total_examples 或者 total_words 必须设置,如果语料 sentences 和提供给 build_vocab 中的相同,那么可以简单地写成 total_examples=self.corpus_count,另外 epochs 参数必须提供,如果我们只需要执行 train() 一次(推荐这么做),可以设置为 epochs=self.iter

注意:如果是 C 编写的模型,那重新载入后,无法继续训练!!!

训练损失计算

如果计算模型时

model.get_latest_training_loss()

# instantiating and training the Word2Vec model
model_with_loss = gensim.models.Word2Vec(
    sentences,
    min_count=1,
    compute_loss=True,
    hs=0,
    sg=1,
    seed=42
)

# getting the training lo
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值