为了提取输入数据的嵌入表示, tensorflow 文档说我们可以使用以下内容:
embed = tf.nn.embedding_lookup(embeddings, input_data)
根据TF documentation ,tf.nn.embedding_lookup函数的第二个参数是ids的张量:
ids: A Tensor with type int32 or int64 containing the ids to be looked up in params.
我的问题是:给定一个句子,比如说,
"Welcome to the world"
如何将其表示并转换为 ids
?在下面的代码中,如何将我的句子转换为input_data
。
from gensim import models
embedding_path = "../embeddings/GoogleNews-vectors-negative300.bin"
w = models.Word2Vec.load_word2vec_format(embedding_path, binary=True)
X = w.syn0
W = tf.Variable(tf.constant(0.0, shape=X.shape),trainable=False, name="W")
embedding_placeholder = tf.placeholder(tf.float32, X.shape)
embedding_init = W.assign(embedding_placeholder)
embed = tf.nn.embedding_lookup(embedding_init, input_data)
sess = tf.Session()
sess.run(embed, feed_dict={embedding_placeholder: X})
最佳答案
我正在寻找类似这样的代码。我不知道 w
的类属性 - 在 gensim 网站中找不到它们。
s = "hello, how are you?"
tokens = tokenize(s)//function that returns a list of the tokens in a sentence
ids = []
for key in tokens:
try:
ids.append(w.vocab[key].index)
except:
ids.append(w.vocab['UNK'].index)
关于python - 使用word2vec预训练向量,如何生成句子的id作为tensorflow中tf.nn.embedding_lookup函数的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41467115/