达观杯文本处理(三)--word2vec

1.Word2Vec

Word2Vec 是 Google 团队2013年推出的,自提出后被广泛应用在自然语言处理任务中,并且受到它的启发,后续出现了更多形式的词向量模型。Word2Vec 主要包含两种模型:Skip-Gram 和 CBOW,值得一提的是,Word2Vec 词向量可以较好地表达不同词之间的相似和类比关系。

参数解释如下:

sg=1 是 skip-gram 算法,对低频词敏感;默认 sg=0 为 CBOW 算法。
size 是输出词向量的维数,值太小会导致词映射因为冲突而影响结果,值太大则会耗内存并使算法计算变慢,一般值取为100到200之间。
window 是句子中当前词与目标词之间的最大距离,3表示在目标词前看3-b 个词,后面看 b 个词(b 在0-3之间随机)。
min_count 是对词进行过滤,频率小于 min-count 的单词则会被忽视,默认值为5。
negative 和 sample 可根据训练结果进行微调,sample 表示更高频率的词被随机下采样到所设置的阈值,默认值为 1e-3。
hs=1 表示层级 softmax 将会被使用,默认 hs=0 且 negative 不为0,则负采样将会被选择使用。
详细参数说明可查看 Word2Vec 源代码。

2.实现

在这里插入图片描述

1.分词

from gensim.models import Word2Vec

#进行分词
def sentence2list(sentence):
    return sentence.strip().split()

2.选取数据大小

#选取2000条数据进行模拟
x_train['word_seg'].head(2000).apply(sentence2list)

3.训练模型

#模型
model = Word2Vec(sentences=sentences_train, sg=1, size=100,  window=5,  min_count=2,  negative=1, sample=0.001, hs=1, workers=4)

4.提取词汇表及vectors,

# 提取词汇表及vectors,
wv=model.wv
vocab_list = wv.index2word
print(len(vocab_list))
word_idx_dict = {}
for idx, word in enumerate(vocab_list):
    word_idx_dict[word] = idx
vectors_arr = wv.vectors
print(len(vectors_arr))
vectors_arr = np.concatenate((np.zeros(100)[np.newaxis, :], vectors_arr), axis=0)#第0位置的vector为'unk'的vector
print(vectors_arr.shape)

5.保存

# 保存
import pickle
f_wordidx = open('word_seg_word_idx_dict.pkl', 'wb')
f_vectors = open('word_seg_vectors_arr.pkl', 'wb')
pickle.dump(word_idx_dict, f_wordidx)
pickle.dump(vectors_arr, f_vectors)
f_wordidx.close()
f_vectors.close()

参考
https://github.com/Heitao5200/DGB/blob/master/feature/feature_code/train_word2vec.py

猜你喜欢

转载自blog.csdn.net/weixin_41781408/article/details/89106158