【发布时间】: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