8

我有一个Word2Vec接受过培训的模型Gensim。我如何在Tensorflowfor中使用它Word Embeddings。我不想在 Tensorflow 中从头开始训练嵌入。有人可以告诉我如何使用一些示例代码来做到这一点吗?

4

1 回答 1

10

假设您有一个字典和 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进入你的卷积或其他什么。我还假设您没有重新训练嵌入,而只是使用它们。希望有帮助

于 2017-03-28T19:45:55.283 回答