TensorFlow has a feature called GradientTape, kinda getting gradients using Monte Carlo method(?).
I'm trying to simulate the gradient of ReLU but this doesn't work on the negative half of 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);
Guess I have to change something at the line y = fx = x
, like adding a if x<=0
but can't figure out how.
The above code prints out:
tf.Tensor([1. 1. 1. 1. 1. 1. 1.], shape=(7,), dtype=float32)
But it is wanted to be:
tf.Tensor([0. 0. 0. 0. 1. 1. 1.], shape=(7,), dtype=float32)