35.2_tanh函数的实现

35.2 tanh函数的实现

y=tanh(x)y = \tanh (x) 时, tanh\tanh 函数的导数为 tanh(x)x=1y2\frac{\partial \tanh(x)}{\partial x} = 1 - y^2 。我们编写如下代码来实现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中。