RNN中输出端的sample采样

来源:互联网 发布:淘宝兼职被骗了怎么办 编辑:程序博客网 时间:2024/05/14 01:59

在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

1 0