35.2_tanh函数的实现
35.2 tanh函数的实现
当 时, 函数的导数为 。我们编写如下代码来实现Tanh类和tanh函数。
dezero/functions.py
classTanh(Function): defforward(self,x): $\mathrm{y} = \mathrm{np.tanh(x)}$ returny defbackward(self,gy): y $=$ self.outputx[0]() $\mathrm{gx} = \mathrm{gy}^{*}$ (1-y\*y) returngx
deftanh(x): returnTanh()x正向传播使用了NumPy的np.tanh方法,而反向传播通过gy*(1-yy)(也可以写成gy(1-y**2))实现。以上就是DeZero中tanh函数的实现。为了便于将来使用,我们将这个tanh函数添加到dezero/functions.py中。