pytorch系列7 —–nn.Sequential讲解

pytorch系列7 —–nn.Sequential讲解nn Sequential

接下来想讲一下参数初始化方式对训练的影响,但是必须要涉及到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

(0)
上一篇 2026年3月19日 下午8:49
下一篇 2026年3月19日 下午8:50


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号