繁体   English   中英

如何在Tensorflow中使用预训练的Word2Vec模型

[英]How to use pretrained Word2Vec model in Tensorflow

我有一个Word2Vec模型,在Gensim训练。 如何在Tensorflow使用它进行Word Embeddings 我不想在Tensorflow中从头开始训练嵌入。 有人可以告诉我如何使用一些示例代码吗?

假设你有一个字典和inverse_dict列表,列表中的索引对应于最常见的单词:

vocab = {'hello': 0, 'world': 2, 'neural':1, 'networks':3}
inv_dict = ['hello', 'neural', 'world', 'networks']

注意inverse_dict索引如何对应于字典值。 现在声明你的嵌入矩阵并获取值:

vocab_size = len(inv_dict)
emb_size = 300 # or whatever the size of your embeddings
embeddings = np.zeroes((vocab_size, emb_size))

from gensim.models.keyedvectors import KeyedVectors                         
model = KeyedVectors.load_word2vec_format('embeddings_file', binary=True)

for k, v in vocab.items():
  embeddings[v] = model[k]

你有嵌入矩阵。 好。 现在让我们假设你想训练样本: x = ['hello', 'world'] 但这对我们的神经网络不起作用。 我们需要整合:

x_train = []
for word in x:  
  x_train.append(vocab[word]) # integerize
x_train = np.array(x_train) # make into numpy array

现在我们很高兴能够即时嵌入我们的样品

x_model = tf.placeholder(tf.int32, shape=[None, input_size])
with tf.device("/cpu:0"):
  embedded_x = tf.nn.embedding_lookup(embeddings, x_model)

现在embedded_x进入你的卷积或其他什么。 我也假设你没有重新训练嵌入,只是简单地使用它们。 希望有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM