在Theano中,有如下定義的函數可供sequence to sequence 模型來使用sample功能:
def sample(preds, temperature=1.0):
# function to sample an index from a probability array
# temperature = (0, 1.0]
# https://github.com/fchollet/keras/blob/master/examples/lstm_text_generation.py
# https://github.com/mosessoh/CNN-LSTM-Caption-Generator/blob/master/utils.py
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.multinomial.html
preds = tf.log(preds) / temperature
exp_preds = tf.exp(preds)
preds = exp_preds / np.sum(exp_preds)
probas = np.random.multinomial(1, preds, 1)
return np.argmax(probas)
注意,在Tensorflow中使用的時候,會因爲Tensor與numpy Array之別而報錯,解決辦法如下:
一方面,可以轉換Tensor 與numpy array的格式,用上面的函數來實現採樣;
另一方面,可以使用
tf.multinomial(logits, num_samples)
函數來實現採樣,詳見該文http://blog.csdn.net/jasonzzj/article/details/60330286