如何用tf.GradientTape模拟ReLU梯度

How to simulate ReLU gradient with tf.GradientTape

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

我正在尝试模拟 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)

以下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