激励函数Activation Function

1、激励函数的作用

不使用激励函数的话,神经网络的每层都只是做线性变换,多层输入叠加后也还是线性变换。因为线性模型的表达能力不够,激励函数可以引入非线性因素。 

2、Torch中的激励函数

import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt

#随便做一些数据来观看函数的图像
x = torch.linspace(-5, 5, 200) #tensor
x_np = x.numpy()
#把tensor类型转换成numpy类型,matplotlib只能用numpy数据类型

#几种常用的激励函数
y_relu = torch.relu(x).numpy()
y_sigmoid = torch.sigmoid(x).numpy()
y_tanh = torch.tanh(x).numpy()
y_softplus = F.softplus(x).numpy() # there's no softplus in torch
#y_softmax = F.softmax(x) softmax比较特殊,关于概率的不能直接显示,可用于分类

plt.figure(1, figsize=(8, 6))
plt.subplot(221) 
plt.plot(x_np, y_relu, c='red', label='relu')
plt.ylim((-1, 5))
plt.legend(loc='best')

plt.subplot(222)
plt.plot(x_np, y_sigmoid, c='red', label='sigmoid')
plt.ylim((-0.2, 1.2))
plt.legend(loc='best')

plt.subplot(223)
plt.plot(x_np, y_tanh, c='red', label='tanh')
plt.ylim((-1.2, 1.2))
plt.legend(loc='best')

plt.subplot(224)
plt.plot(x_np, y_softplus, c='red', label='softplus')
plt.ylim((-0.2, 6))
plt.legend(loc='best')

plt.show()

猜你喜欢

转载自www.cnblogs.com/funnything/p/11024491.html