三 深度学习笔记:神经网络之九种激活函数Sigmoid、tanh、ReLU、R( 二 )


在输入 x < 0 x < 0x
函数图像:
优点:
缺点:
代码实现:
"""pytorch 神经网络"""import torch.nn as nnLR=nn.LeakyReLU(inplace=True)
# tensorflow实现LeakyRelu函数import tensorflow as tfdef LeakyRelu(x,leak = 2,name = 'LeakyRelu'):with tf.variable_scope(name):f1 = 0.5*(1+leak)f2 = 0.5*(1-leak)return f1*x+f2*tf.abs(x)if __name__ == '__main__':a = LeakyRelu(4.0)print(a)
运行结果:
9.ELU
函数定义:
函数图像:
右侧的线性部分能够缓解梯度消失,左侧的软饱和能够对于输入变化鲁棒.而且收敛速度更快.
代码实现:
# ELU函数在numpy上的实现import numpy as npimport matplotlib.pyplot as pltdef elu(x, a):y = x.copy()for i in range(y.shape[0]):if y[i] < 0:y[i] = a * (np.exp(y[i]) - 1)return yif __name__ == '__main__':x = np.linspace(-50, 50)a = 0.5y = elu(x, a)print(y)plt.plot(x, y)plt.title('elu')plt.axhline(ls='--',color = 'r')plt.axvline(ls='--',color = 'r')# plt.xticks([-60,60]),plt.yticks([-10,50])plt.show()
运行结果:
10.Swish
class Swish(nn.Module):def __init__(self):super(Swish, self).__init__()def forward(self, x):x = x * F.sigmoid(x)return x
11.Mish
相比Swish有0.494%的提升,相比ReLU有1.671%的提升 。
为什么Mish表现的更好:
#-------------------------------------------------##MISH激活函数#-------------------------------------------------#class Mish(nn.Module):def __init__(self):super(Mish, self).__init__()def forward(self, x):return x * torch.tanh(F.softplus(x))
12.
函数定义:
Vi表示第i个神经元的输出,其实就是在输出后面套一个这个函数
函数作用:用于处理多分类问题,将N个输出的数值全部转换为N个相对概率 。比如说
这里有个特点,就是这里所有的概率值全部加起来等于1. S1 = 0.8390,对应的概率最大,概率越大预测为第1类的可能性更大 。
代码简单实现:
# Softmax实现import numpy as npdef Softmax(x):n = np.exp(x)/np.sum(np.exp(x))return nif __name__ == '__main__':x = [3.0,1.0,2.0]a = Softmax(x)print(a)
【三深度学习笔记:神经网络之九种激活函数Sigmoid、tanh、ReLU、R】运行结果:
一维和二维矩阵的代码实现:
# Softmax二维和三维矩阵的实现import numpy as npdef Softmax(x):print("orig_shape", x.shape)if len(x.shape) > 1:# 矩阵 轴用来为超过一维的数组定义的属性,二维数据拥有两个轴:第0轴沿着行的垂直往下,第1轴沿着列的方向水平延伸 。# 关键词:轴具有方向,且axis=0,即0轴,从上到下;axis=1,即1轴,从左到右 。axis=-1也就是代表倒数第一个,如果对于矩阵是一个shape=[3,4,5],axis=-1就等于axis=2,也就是得到一个[3,4]的矩阵,tmp = np.max(x, axis=1)x -= tmp.reshape((x.shape[0], 1)) # 变为两行一列x = np.exp(x)y = x / np.sum(x, axis=1).reshape((x.shape[0], 1))print("matrix")print(y)return yelse:# 向量x -= np.max(x)# scores becomes [-666, -333, 0]y = np.exp(x) / np.sum(np.exp(x))print("Vector quantity")print(y)return yif __name__ == '__main__':x = np.array([1,2,3,4])x1 = np.array([[1,2,3,4],[1,2,3,4]])Softmax(x)Softmax(x1)
运行结果: