TensorFlow:如何将单词嵌入写入fi

2024-04-26 06:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我是TF的新手。我在网上找到了一个教程。本教程构建单词嵌入,然后使用余弦sim计算单词之间的相似度(对于给定的集合)。我要做的是将生成的单词嵌入存储到一个文件中。在

以下是代码(片段):

embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0)) 
embed = tf.nn.embedding_lookup(embeddings, input_word_index_list)   

weights = tf.Variable(tf.truncated_normal([vocabulary_size,embedding_size],stddev=1.0 / math.sqrt(embedding_size)))
biases = tf.Variable(tf.zeros([vocabulary_size]))
hidden_out = tf.matmul(embed,tf.transpose(weights)) + biases


train_one_hot = tf.one_hot(train_context, vocabulary_size)
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=hidden_out, labels=train_one_hot))
optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(cross_entropy)

...
...

norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm

final_embeddings = normalized_embeddings.eval()

for keys in reverse_dictionary_dict:
    embedings_to_file = tf.nn.embedding_lookup(final_embeddings,keys)
    writeEmbeddings2File.write(str(keys)+'\t'+ str(reverse_dictionary_dict[keys])+'\t'+tf.Print(embedings_to_file,embedings_to_file))
    writeEmbeddings2File.write('\n')
writeEmbeddings2File.close() 

错误:

^{pr2}$

我还尝试了基本的python打印功能。这导致 印刷

0   UNK Tensor("embedding_lookup:0", shape=(300,), dtype=float32)
1   the Tensor("embedding_lookup_1:0", shape=(300,), dtype=float32)

关于如何解决这个问题有什么建议吗?在


Tags: sizetftrainnnembeddingkeyslookup单词