多层感知机实现

本文介绍了多层感知机的概念,强调了激活函数在神经网络中引入非线性的重要性。ReLU、Sigmoid和tanh作为常见的激活函数被讨论,并通过代码展示了它们的图像及导数图像。此外,还提供了多层感知机的PyTorch实现,展示了一个包含ReLU和线性层的简单模型。
摘要由CSDN通过智能技术生成

激活函数

前两节实现的linear model 和 softmax model 是单层神经网络,只包含一个输入层和一个输出层,因为输入层不对数据进行transformation,所以只算一层输出层。
多层感知机(mutilayer preceptron)加入了隐藏层,将神经网络的层级加深,因为线性层的串联结果还是线性层,所以必须在每个隐藏层之后添加激活函数,即增加model的非线性能力,使得model的function set变大。
ReLU,Sigmoid, tanh是三个常见的激活函数,分别做出它们的函数图像以及导数图像。

#画图使用
def xyplot(x,y,name,size):
	plt.figure(figsize=size)
	plt.plot(x.detach().numpy(),y.detach().numpy())
	plt.xlabel('x')
	plt.ylabel(name+'(x)')
	plt.show()
#relu
x = torch.arange(-8,8,0.01,requires_grad=True)
y = x.relu()
xyplot(x,y,'relu')

在这里插入图片描述

y.sum().backward()
xyplot(x,x.grad,'grad of relu')

在这里插入图片描述
其它两个激活函数的图像画法类似,分别为x.sigmoid(),x.tanh()

多层感知机的PyTorch实现

实际上多层感知机不过是在linear变换之后添加relu操作,在output layer进行softmax操作

def relu(x):
	return torch.max(input=x,others,other=torch.tensor(0.0))

max这个方法除了返回tensor中的最大值,还有和maximum函数一样的作用,将input和other进行element-wise的比较,返回二者中的最大值,shape不变。

class MulPeceptron(nn.Module):
    def __init__(self,in_features,out_features):
        super().__init__()
        self.fc = nn.Linear(in_features=in_features,out_features=256)
        self.out = nn.Linear(in_features=256,out_features=out_features)
    def forward(self,t):
        t = t.flatten(start_dim=1)
        t = self.fc(t)
        t = F.relu(t)
        t = self.out(t)
        return t

这里就不从零开始实现了,因为softmax和linear model手写过以后,这个只是增加了一个矩阵乘法和一个ReLU操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值