【无标题】

该代码示例展示了如何在Python中使用torch库实现ReLU和LeakyReLU激活函数,并通过matplotlib绘制它们的图形对比。ReLU在负区为零,而LeakyReLU有一个小的负斜率,避免了ReLU的‘死亡神经元’问题。
#!/usr/bin/python
# -*- coding:utf8 -*-
import torch
import matplotlib.pyplot as plt
def relu(z):
    return torch.maximum(z,torch.as_tensor(0.))
#带泄露值relu
def leaky_relu(z,negative_slope=0.1):
    a1=(torch.can_cast((z>0).dtype,torch.float32)*z)
    a2=(torch.can_cast((z<=0).dtype,torch.float32)*(negative_slope*z))
    return a1+a2
z=torch.linspace(-10,10,10000)
plt.figure()
plt.plot(z.tolist(),relu(z).tolist(),color='#e4007f',label='ReLU Function')
plt.plot(z.tolist(),leaky_relu(z).tolist(),color='#f19ec2',linestyle='--',label='Leaky_ReLU')
ax=plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
plt.legend(loc='upper left',fontsize='large')
plt.savefig('fw-relu-leakyrelu.pdf')
plt.show()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值