激励函数通常是非线性的,其通过对线性矩阵运算结果的非线性变化,使用神经网络得以拟合任意函数
1. 数据准备
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import matplotlib.pyplot as plt
# fake data
x = torch.linspace(-5, 5, 200) # x data (tensor), shape=(100, 1)
x = Variable(x)
x_np = x.data.numpy() # numpy array for plotting
2. 常见非线性激励函数
# following are popular activation functions
y_relu = torch.relu(x).data.numpy()
y_sigmoid = torch.sigmoid(x).data.numpy()
y_tanh = torch.tanh(x).data.numpy()
y_softplus = F.softplus(x).data.numpy() # there's no softplus in torch
y_softmax = torch.softmax(x, dim=0).data.numpy()
#softmax is a special kind of activation function, it is about probability
- Relu , Tanh , Sigmoid 是最常见的激励函数,常用与 CNN(Relu),RNN(Tanh)等连用
- Softmax 函数亦是常见的激励函数,多用于预测与分类问题,其可将任意输出转换为概率
- Softplus 函数在Torch 中不存在,不常用到
3. 图像可视化——Matplolib
# plt to visualize these activation function
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()
1.plt.figure ('title','figsize'):初始化plt框图,figsize表示该框图的结构
2.plt.subplot('num-1','num-2','num-3'):用于在plt框图中构建子图,num-1与num-2表示子图的二维位置,num-3表示框图顺序
plt.show():显示plt图像