激活函数:
1, relu
2, sigmoid
3, tanh
4, (Mish)
#1, relu激活函数 ReLU(x)=max(x,0)
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = x.relu() # 激活函数
plt.figure(1, figsize=(8, 6))
plt.subplot(1, 2, 1)
plt.plot(x.detach().numpy(), y.detach().numpy())
plt.xlabel('x')
plt.ylabel('relu' + '(x)')
plt.subplot(1, 2, 2)
y.sum().backward()
plt.plot(x.detach().numpy(), x.grad.detach().numpy())
plt.xlabel('x')
plt.ylabel('grad of relu' + '(x)')
plt.savefig('relu.png')
plt.show()
# 2, sigmoid函数: sigmoid(x) =1 / (1 + exp(−x))
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = x.sigmoid() # 激活函数
plt.figure(2, figsize=(8, 6))
plt.subplot(1, 2, 1)
plt.plot(x.detach().numpy(), y.detach().numpy())
plt.xlabel('x')
plt.ylabel('sigmoid' + '(x)')
plt.subplot(1, 2, 2)
y.sum().backward()
plt.plot(x.detach().numpy(), x.grad.detach().numpy())
plt.xlabel('x')
plt.ylabel('grad of sigmoid' + '(x)')
plt.savefig('sigmoid.png')
plt.show()
# 3, tanh(双曲正切)函数:tanh(x)= (1−exp(−2x)) / (1+exp(−2x))
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = x.tanh() # 激活函数
plt.figure(3, figsize=(8, 6))
plt.subplot(1, 2, 1)
plt.plot(x.detach().numpy(), y.detach().numpy())
plt.xlabel('x')
plt.ylabel('tanh' + '(x)')
plt.subplot(1, 2, 2)
y.sum().backward()
plt.plot(x.detach().numpy(), x.grad.detach().numpy())
plt.xlabel('x')
plt.ylabel('grad of tanh' + '(x)')
plt.savefig('tanh.png')
plt.show()
# 4, Mish函数: Mish(x) = x * tanh(log(1 + exp(x)))
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = x * (torch.tanh(F.softplus(x))) # 实现
plt.figure(4, figsize=(8, 6))
plt.subplot(1, 2, 1)
plt.plot(x.detach().numpy(), y.detach().numpy())
plt.xlabel('x')
plt.ylabel('Mish' + '(x)')
plt.subplot(1, 2, 2)
y.sum().backward()
plt.plot(x.detach().numpy(), x.grad.detach().numpy())
plt.xlabel('x')
plt.ylabel('grad of Mish' + '(x)')
plt.savefig('Mish.png')
plt.show()