我想做同样的事情,这就是我想出的,改编自他们的一些演示代码。我不完全确定这是正确的,但它似乎产生了合理的值。
def get_probability_of_next_word(sess, t, vocab, prefix_words, query):
"""
Return the probability of the given word based on the sequence of prefix
words.
:param sess: Tensorflow session object
:param t: Tensorflow ??? object
:param vocab: Vocabulary model, maps id <-> string, stores max word chard id length
:param list prefix_words: List of words that appear before this one.
:param str query: The query word
"""
targets = np.zeros([BATCH_SIZE, NUM_TIMESTEPS], np.int32)
weights = np.ones([BATCH_SIZE, NUM_TIMESTEPS], np.float32)
if not prefix_words or prefix_words[0] != "<S>":
prefix_words.insert(0, "<S>")
prefix = [vocab.word_to_id(w) for w in prefix_words]
prefix_char_ids = [vocab.word_to_char_ids(w) for w in prefix_words]
inputs = np.zeros([BATCH_SIZE, NUM_TIMESTEPS], np.int32)
char_ids_inputs = np.zeros(
[BATCH_SIZE, NUM_TIMESTEPS, vocab.max_word_length], np.int32)
inputs[0, 0] = prefix[0]
char_ids_inputs[0, 0, :] = prefix_char_ids[0]
softmax = sess.run(t['softmax_out'],
feed_dict={t['char_inputs_in']: char_ids_inputs,
t['inputs_in']: inputs,
t['targets_in']: targets,
t['target_weights_in']: weights})
return softmax[0, vocab.word_to_id(query)]
示例用法
vocab = CharsVocabulary(vocab_path, MAX_WORD_LEN)
sess, t = LoadModel(model_path, ckptdir + "/ckpt-*")
result = get_probability_of_next_word(sess, t, vocab, ["Hello", "my", "friend"], "for")
给出的结果8.811023e-05
。请注意,CharsVocabulary
并且LoadModel
与 repo 中的内容略有不同。
另请注意,此功能非常慢。也许有人知道如何改进它。