@tf.custom_gradient 自定义sign的梯度

本文介绍了如何在TensorFlow中使用`@tf.custom_gradient`装饰器来自定义sign操作的梯度计算,包括输入和输出的处理以及针对两个参数的测试示例。
摘要由CSDN通过智能技术生成

https://blog.csdn.net/LoseInVain/article/details/83108001
在这里插入图片描述https://github.com/tensorflow/tensorflow/blob/7dd20b844ced19610f8fa67be61d93948563ac43/tensorflow/python/ops/custom_gradient.py

输入

import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
@tf.custom_gradient
def DoublySign(x):
    def grad(dy):
        '''
        dy 是从反向而言的上一层的梯度
        '''
        cond = (x >= -1) & (x <= 1)
        zeros = tf.zeros_like(dy)
        return tf.where(cond,dy,zeros) 
    # 这里相当于是在自己手动计算梯度,如果在-1和1之间,将sign的函数梯度修改为1,根据链式法则,梯度为dy*1=dy
    # 而其他情况下,梯度为dy*0=0
    # tf.where 和 tf.cond 的区别 https://blog.csdn.net/xiadimichen14908/article/details/83592282
    return tf.sign(x),grad


x = tf.constant(np.linspace(-2,2,100))
y = DoublySign(x)
grad = tf.gradients(y,x)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(x.eval())
    print(y.eval())
    print(sess.run(grad))
    plt.figure(figsize=(10,5))
    plt.subplot(1,2,1)
    ax = plt.gca()         # get current axis 获得坐标轴对象
    plt.xlabel('x&
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值