
那怎么构建人工神经网络中的神经元呢?





- import torch
- import matplotlib.pyplot as plt
-
- # 一. 函数原图像
- # 函数图像
- x = torch.linspace(-20,20,1000)
- # 1. 输入值x通过sigmoid函数转换成激活值y
- # y = torch.sigmoid(x)
-
- # 2. 输入值x通过tanh函数转换成激活值y
- # y = torch.tanh(x)
-
- # 3. 输入值x通过relu函数转换成激活值y
- y = torch.relu(x)
-
- # 画图
- # 创建画布和坐标轴
- _,axes = plt.subplots(1,2)
- axes[0].plot(x,y)
- axes[0].grid()
-
-
- # 二. 导数图像
- x = torch.linspace(-20,20,1000,requires_grad=True)
-
- # torch.sigmoid(x).sum().backward()
- # torch.tanh(x).sum().backward()
- torch.relu(x).sum().backward()
-
- # x.detach()输入值x的数值 x.grad 计算梯度 求导
- axes[1].plot(x.detach(),x.grad)
- axes[1].grid()
- plt.show()
- import torch
- import torch.nn as nn
-
- # 1. 模型结构
- layer = nn.Linear(in_features=3,out_features=5)
-
- # nn.init.uniform_(layer.weight) # 1. 均匀分布
- # nn.init.normal_(layer.weight) # 2. 正态分布
- # nn.init.constant_(layer.weight,5) # 3. 固定初始化
- # nn.init.zeros_(layer.weight) # 4. 全0 (对bias初始化)(默认)
- # nn.init.ones_(layer.weight) # 5. 全1 (对bias初始化),其他对weight
-
- # nn.init.kaiming_normal_(layer.weight) # 6. 凯明(正态分布)
- # nn.init.kaiming_uniform_(layer.weight) # 凯明(均匀分布)
-
- # nn.init.xavier_normal_(layer.weight) # 7. xavier(正态分布)(默认)
- nn.init.xavier_uniform_(layer.weight) # xavier(均匀分布)
-
- print(layer.weight.data)

编码设计如下:
1.第1个隐藏层:权重初始化采用标准化的xavier初始化 激活函数使用sigmoid
2.第2个隐藏层:权重初始化采用标准化的He初始化激活函数采用relu3out输出层线性层 假若二分类,采用softmax做数据归一化
- import torch
- import torch.nn as nn
- from torchsummary import summary
-
- # 构建神经网络
- # 1. 定义继承自nn.Module的模型类
- class model(nn.Module):
- # 2. 在__init__方法中定义网络中的层结构
- def __init__(self):
- # 调用父类的初始化属性值
- super(model,self).__init__()
- # 创建第一个隐藏层模型, 3个输入特征,3个输出特征
- self.layer1 = nn.Linear(3,3)
- # 初始化权重
- nn.init.kaiming_normal_(self.layer1.weight)
- # 创建第二个隐藏层模型, 3个输入特征(上一层的输出特征),2个输出特征
- self.layer2 = nn.Linear(3,2)
- # 初始化权重
- nn.init.kaiming_normal_(self.linear2.weight)
- # 创建输出层模型
- self.out = nn.Linear(2,2)
-
- # 3. 在forward方法中定义数据传输方式
- def forward(self,x):
- # 数据经过第一个线性层
- h1 = self.layer1(x)
- # 使用relu激活函数
- h1 = torch.relu(h1)
- # 数据经过第二个线性层
- h2 = self.layer2(h1)
- # 使用relu激活函数
- h2 = torch.relu(h2)
- # 数据经过输出层
- out = self.out(h2)
- # 使用softmax激活函数
- out = torch.softmax(out,dim=-1)
- return out
-
- if __name__ == '__main__':
- # 创建model对象
- net = model()
- # summary(net,input_size=(3,),batch_size=5)
- # 随机产生数据
- x = torch.randn(5,3)
- y = net(x)
- print(y.shape)
- # 查看模型参数
- for name,params in net.named_parameters():
- print(name)
- print(params)