RNN中输出端的sample采样

在Theano中,为sequence to sequence模型实现sample功能,需要特定的函数。当尝试在Tensorflow中应用时,由于Tensor与numpy数组的不兼容会导致错误。解决方法包括转换数据类型或利用特定函数进行采样操作。
摘要由CSDN通过智能技术生成

在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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值