python - Gensim Word2Vec 从预训练模型中选择少量词向量
问题描述
我在 gensim 中有一个大型的预训练 Word2Vec 模型,我想从中将预训练的词向量用于我的 Keras 模型中的嵌入层。
问题是嵌入大小很大,我不需要大部分词向量(因为我知道哪些词可以作为输入出现)。所以我想摆脱它们以减小嵌入层的大小。
有没有办法根据单词白名单保留所需的单词向量(包括对应的索引!)?
解决方案
感谢这个答案(我已经稍微更改了代码以使其更好)。您可以使用此代码来解决您的问题。
我们有我们所有的次要单词集restricted_word_set
(它可以是列表或集合)并且w2v
是我们的模型,所以这里是函数:
import numpy as np
def restrict_w2v(w2v, restricted_word_set):
new_vectors = []
new_vocab = {}
new_index2entity = []
new_vectors_norm = []
for i in range(len(w2v.vocab)):
word = w2v.index2entity[i]
vec = w2v.vectors[i]
vocab = w2v.vocab[word]
vec_norm = w2v.vectors_norm[i]
if word in restricted_word_set:
vocab.index = len(new_index2entity)
new_index2entity.append(word)
new_vocab[word] = vocab
new_vectors.append(vec)
new_vectors_norm.append(vec_norm)
w2v.vocab = new_vocab
w2v.vectors = np.array(new_vectors)
w2v.index2entity = np.array(new_index2entity)
w2v.index2word = np.array(new_index2entity)
w2v.vectors_norm = np.array(new_vectors_norm)
警告:当你第一次创建模型时,
vectors_norm == None
如果你在那里使用这个函数,你会得到一个错误。vectors_norm
将numpy.ndarray
在第一次使用后获得该类型的值。所以在使用该函数之前,请尝试类似most_similar("cat")
这样的操作,以便vectors_norm
不等于None
.
它根据Word2VecKeyedVectors重写与单词相关的所有变量。
用法:
w2v = KeyedVectors.load_word2vec_format("GoogleNews-vectors-negative300.bin.gz", binary=True)
w2v.most_similar("beer")
[('beers', 0.8409687876701355),
('lager', 0.7733745574951172),
('Beer', 0.71753990650177),
('drinks', 0.668931245803833), ('lagers',
0.6570086479187012),
('Yuengling_Lager', 0.655455470085144),
( 'microbrew', 0.6534324884414673),
('Brooklyn_Lager', 0.6501551866531372),
('suds', 0.6497018337249756),
('brewed_beer', 0.6490240097045898)]
restricted_word_set = {"beer", "wine", "computer", "python", "bash", "lagers"}
restrict_w2v(w2v, restricted_word_set)
w2v.most_similar("beer")
[('lagers', 0.6570085287094116),
('wine', 0.6217695474624634),
('bash', 0.20583480596542358),
('computer', 0.06677375733852386),
('python', 0.090059472)]573
它也可以用于删除一些单词。
推荐阅读
- service - 在 CHDIR 生成 /opt/Informer5/informer5.sh 步骤失败:没有这样的文件或目录
- pentaho - Pentaho Kettle - 动态获取文件名
- javascript - Ext js 5.0.1 列自定义排序
- python - 从 java 客户端订阅到 python opcua 服务器不起作用
- vue.js - Vuejs的v-for中如何处理组件发出的事件
- sql - 拆分字段并添加小数点以创建数值 SQL
- redis - redis pub sub 仅适用于某组键?
- protractor - 如何使用量角器执行 .exe 文件?
- ruby-on-rails - 编组数据库对象是否安全?
- vba - 无法通过 vba 打开 Microsoft Office 文档映像