接下来想讲一下参数初始化方式对训练的影响,但是必须要涉及到pytorch的自定义参数初始化,然而参数初始化又包括在不同结构定义中初始化方式,因而先讲一下pytorch中的nn.Sequential
nn.Sequential
A sequential container. Modules will be added to it in the order they are passed in the constructor. Alternatively, an ordered dict of modules can also be passed in.
一个有序的容器,神经网络模块将按照在传入构造器的顺序依次被添加到计算图中执行,同时以神经网络模块为元素的有序字典也可以作为传入参数。
看一下例子:
# Example of using Sequential model = nn.Sequential( nn.Conv2d(1,20,5), nn.ReLU(), nn.Conv2d(20,64,5), nn.ReLU() ) # Example of using Sequential with OrderedDict model = nn.Sequential(OrderedDict([ ('conv1', nn.Conv2d(1,20,5)), ('relu1', nn.ReLU()), ('conv2', nn.Conv2d(20,64,5)), ('relu2', nn.ReLU()) ]))
接下来在看一下forward函数的实现:
因为每一个module都继承于nn.Module,都会实现__call__与forward函数,具体讲解点击这里,所以forward函数中通过for循环依次调用添加到self._module中的子模块,最后输出经过所有神经网络层的结果

下面是简单的三层网络结构的例子:
# hyper parameters in_dim=1 n_hidden_1=1 n_hidden_2=1 out_dim=1 class Net(nn.Module): def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim): super().__init__() self.layer = nn.Sequential( nn.Linear(in_dim, n_hidden_1), nn.ReLU(True), nn.Linear(n_hidden_1, n_hidden_2), nn.ReLU(True), # 最后一层不需要添加激活函数 nn.Linear(n_hidden_2, out_dim) ) def forward(self, x): x = self.layer(x) return x
上面的代码就是通过Squential将网络层和激活函数结合起来,输出激活后的网络节点。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/204174.html原文链接:https://javaforall.net
