【问题标题】:How to simulate ReLU gradient with tf.GradientTape如何使用 tf.GradientTape 模拟 ReLU 梯度
【发布时间】:2020-01-26 08:22:59
【问题描述】:

TensorFlow 有一个名为 GradientTape 的功能,有点像使用蒙特卡洛方法(?)获取梯度。

我正在尝试模拟 ReLU 的梯度,但这不适用于 X 的负半部分。

#colab or ipython reset
%reset -f

#libs
import tensorflow as tf;

#init
tf.enable_eager_execution();

#code
x = tf.convert_to_tensor([-3,-2,-1,0,1,2,3],dtype=tf.float32);

with tf.GradientTape() as t:
  t.watch(x);
  y = fx = x; #THIS IS JUST THE POSITIVE HALF OF X

dy_dx = t.gradient(y,x);
print(dy_dx); 

我想我必须在y = fx = x 行更改一些内容,例如添加if x<=0,但不知道怎么做。

上面的代码打印出来:

tf.Tensor([1. 1. 1. 1. 1. 1. 1.], shape=(7,), dtype=float32)

但它是想要的:

tf.Tensor([0. 0. 0. 0. 1. 1. 1.], shape=(7,), dtype=float32)

【问题讨论】:

    标签: tensorflow gradient derivative activation relu


    【解决方案1】:

    以下grad函数模拟ReLU函数的条件X,但我不知道它是否是建议的,建议的方法:

    #ipython
    %reset -f
    
    #libs
    import tensorflow as tf;
    import numpy      as np;
    
    #init
    tf.enable_eager_execution();
    
    #code
    X = tf.convert_to_tensor([-3,-2,-1,0,1,2,3], dtype=tf.float32);
    
    with tf.GradientTape() as T:
      T.watch(X);
      Y = Fx = X;
    #end with
    
    Dy_Dx = T.gradient(Y,X);
    #print(Dy_Dx);
    
    #get gradient of function Fx with conditional X
    def grad(Y,At):
      if (At<=0): return 0;
    
      for I in range(len(X)):
        if X[I].numpy()==At:
          return Dy_Dx[I].numpy();
    #end def
    
    print(grad(Y,-3));
    print(grad(Y,-2));
    print(grad(Y,-1));
    print(grad(Y,-0));
    print(grad(Y,1));
    print(grad(Y,2));
    print(grad(Y,3));
    
    print("\nDone.");
    #eof
    

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 2020-03-28
      • 2018-03-19
      • 2020-10-31
      • 1970-01-01
      • 2019-08-30
      相关资源
      最近更新 更多