如何使用tf.GradientTape模拟ReLU梯度

时间:2019-09-26 05:48:37

标签: tensorflow gradient derivative activation relu

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)

1 个答案:

答案 0 :(得分:0)

下面的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