activation function (激活函数)

1.神经网络产生的数据一般是线性的,而我们现实生活中遇到的问题大多数的问题是非线性的,因此激活函数就出现了。激活函数必须是可微分的,要根据具体的情况选择合适的激活函数,不然会造成梯度爆炸或是梯度消失。

2.常见的激活函数有Relu、Sigmoid、tanh等。

CNN中常用Relu.

RNN中常用tanh、Relu.

3.代码实现

import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt

#fake data
x=torch.linspace(-5,5,200)
x=Variable(x)
#if you want to plot
#the data should a numpy form
x_np=x.data.numpy()

y_relu=F.relu(x).data.numpy()
y_sigmoid=F.sigmoid(x).data.numpy()
y_tanh=F.tanh(x).data.numpy()
y_softplus=F.softplus(x).data.numpy()
#softmax is special,can't plot
#this is about probability
#we can use softmax to classification

#plot
#1 is the name of figure
plt.figure(1,figsize=(8,6))
#the figure is divided 4  part
#respectively are 1,2,3,4
plt.subplot(221)
#x_np is the x axis value
#y_relu is the y axis value
#lable is the legend
plt.plot(x_np,y_relu,c="red",label="relu")
# (-1,5) is the scope of the y axis
plt.ylim(-1,5)
# the best location of the legend
plt.legend(loc="best")

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

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

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

plt.show()

猜你喜欢

转载自blog.csdn.net/xs_211314/article/details/82377621
今日推荐