tensorflow学习笔记(二十七):leaky relu

tensorflow leaky relu

tensorflow 0.12.0及之前,都没有内置的leaky relu函数,那么我们如何实现leaky relu函数呢?

方法1

def relu(x, alpha=0., max_value=None):
    '''ReLU.

    alpha: slope of negative section.
    '''
    negative_part = tf.nn.relu(-x)
    x = tf.nn.relu(x)
    if max_value is not None:
        x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX),
                             tf.cast(max_value, dtype=_FLOATX))
    x -= tf.constant(alpha, dtype=_FLOATX) * negative_part
    return x

方法2

x = tf.maximum(alpha*x,x)

这两种方法,在BP的时候,梯度都会被正确的计算的。
另外,关于tf.clip...函数在BP的时候,梯度也是会被正确计算的

import tensorflow as tf
w1 = tf.Variable(0) #0或5时,打印出来1, 2时打印出来1,6时打印出来0,-1时打印出来0
g = tf.clip_by_value(w1, 0, 5)
grad = tf.gradients(g, [w1])

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    print(sess.run(grad))

参考资料
https://groups.google.com/a/tensorflow.org/forum/#!topic/discuss/V6aeBw4nlaE

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值