本文共 2632 字,大约阅读时间需要 8 分钟。
# Example of using Sequentialmodel = nn.Sequential( nn.Conv2d(1,20,5), nn.ReLU(), nn.Conv2d(20,64,5), nn.ReLU() )
# Example of using Sequential with OrderedDictmodel = nn.Sequential(OrderedDict([ ('conv1', nn.Conv2d(1,20,5)), ('relu1', nn.ReLU()), ('conv2', nn.Conv2d(20,64,5)), ('relu2', nn.ReLU()) ]))
所有网络的基类。
我们的模型也应该继承这个类。
Modules也可以包含其它Modules,允许使用树结构嵌入他们。我们可以将子模块赋值给模型属性。
init中定义每个神经层的神经元个数,和神经元层数;
forward是继承nn.Moudule中函数,来实现前向反馈(加上激活函数) 。
import torch.nn as nnimport torch.nn.functional as Fclass Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5) # submodule: Conv2d self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
class 神经网络模型名字(nn.Module): # 定义初始化函数,在类实例化时会自动调用,其中self 代表的是类的实例 # 类似于c++中的默认构造函数 def __init__(self, 参数列表): super(神经网络模型名字, self).__init__() self.layer1 = nn.Linear(num_input, num_hidden) self.layer2 = nn.Sequential(...) ... 以上主要是定义需要用的网络层 # 定义前向传播函数 def forward(self, x): x1 = self.layer1(x) x2 = self.layer2(x) x = x1 + x2 ... return x
import torch.nn as nnimport torch.nn.functional as Fclass Net(nn.Module): def __init__(self, n_feature, n_hidden, n_output): # 继承__init__函数 super(Net, self).__init__() # 定义网络的各层 self.hidden = nn.Linear(n_feature, n_hidden) self.predict = nn.Linear(n_hidden, n_output) # 实现所有层的连接关系。 def forward(self, x): # 输入x首先在隐藏层经过激励函数的计算 x = F.relu(self.hidden(x)) # 输出层输出预测值 x = self.predict(x) return xnet1 = Net(1, 10, 1)print(net1)print(type(net1))# 快速搭建神经网络:Sequential方式# 模板:网络名称 = torch.nn.Sequential()net2 = nn.Sequential( nn.Linear(1, 10), nn.ReLU(), nn.Linear(10, 1))print(net2)print(type(net2))
Net( (hidden): Linear(in_features=1, out_features=10, bias=True) (predict): Linear(in_features=10, out_features=1, bias=True))Sequential( (0): Linear(in_features=1, out_features=10, bias=True) (1): ReLU() (2): Linear(in_features=10, out_features=1, bias=True))
转载地址:http://ubugf.baihongyu.com/