Tanh 激活函数及求导过程 | 您所在的位置:网站首页 › tanc的导数 › Tanh 激活函数及求导过程 |
原函数: 导数: 先化简为 替代: 因为 所以:
又:
把上式的(2)、(3) 带入(1),得到 作用:非常优秀,几乎适合所有的场景。 缺点:该导数在正负饱和区的梯度都会接近于 0 值,会造成梯度消失。还有其更复杂的幂运算。 可视化: 可视化代码实现: import math import matplotlib.pyplot as plt import numpy as np import mpl_toolkits.axisartist as axisartist # Tanh 激活函数 class Tanh: # 原函数 def forward(self, x): return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)) # 导数 def backward(self, outx): tanh = (np.exp(outx) - np.exp(-outx)) / (np.exp(outx) + np.exp(-outx)) return 1 - math.pow(tanh, 2) # 画图 def Axis(fig, ax): #将绘图区对象添加到画布中 fig.add_axes(ax) # 隐藏坐标抽 ax.axis[:].set_visible(False) # new_floating_axis 创建新的坐标 ax.axis["x"] = ax.new_floating_axis(0, 0) # 给 x 轴创建箭头线,大小为1.0 ax.axis["x"].set_axisline_style("->", size = 1.0) # 给 x 轴箭头指向方向 ax.axis["x"].set_axis_direction("top") # 同理,创建 y 轴 ax.axis["y"] = ax.new_floating_axis(1, 0) ax.axis["y"].set_axisline_style("->", size = 1.0) ax.axis["y"].set_axis_direction("right") # 返回间隔均匀的100个样本,计算间隔为[start, stop]。 x = np.linspace(-10, 10, 100) y_forward = [] y_backward = [] def get_list_forward(x): for i in range(len(x)): y_forward.append(Tanh().forward(x[i])) return y_forward def get_list_backward(x): for i in range(len(x)): y_backward.append(Tanh().backward(x[i])) return y_backward y_forward = get_list_forward(x) y_backward = get_list_backward(x) #创建画布 fig = plt.figure(figsize=(12, 12)) #创建绘图对象ax ax = axisartist.Subplot(fig, 111) Axis(fig, ax) # 设置x, y轴范围 plt.ylim((-2, 2)) plt.xlim((-10, 10)) # 原函数,forward function plt.plot(x, y_forward, color='red', label='$f(x) = tanh(x)$') plt.legend() # 导数, backward function plt.plot(x, y_backward, label='f(x)\' = 1-(tanh)^2') plt.legend() plt.show()
|
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |