Created
July 19, 2021 18:36
-
-
Save lazuxd/22c7766c973b603fb800b437ba90a8a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sample_word(vocabulary: list, prob: np.ndarray, threshold: float) -> str: | |
# sample a word from the vocabulary according to 'prob' | |
# probability distribution (the softmax output of our model) | |
prob = prob.tolist() | |
vocab_prob = [[vocabulary[i], prob[i]] for i in range(len(prob))] | |
vocab_prob.sort(reverse=True, key=lambda e: e[1]) | |
s = 0 | |
for i in range(len(vocab_prob)): | |
if s > threshold: | |
vocab_prob[i][1] = 0 | |
s += vocab_prob[i][1] | |
vocab = [w for w, p in vocab_prob] | |
prob = np.array([p/s for w, p in vocab_prob]) | |
return np.random.choice(vocab, p=prob) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment