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

问题描述 投票:0回答:1

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个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.