浅析PyTorch中nn.Module的使用
作者:Steven·简谈 时间:2021-10-29 14:04:53
torch.nn.Modules 相当于是对网络某种层的封装,包括网络结构以及网络参数和一些操作
torch.nn.Module 是所有神经网络单元的基类
查看源码
初始化部分:
def __init__(self):
self._backend = thnn_backend
self._parameters = OrderedDict()
self._buffers = OrderedDict()
self._backward_hooks = OrderedDict()
self._forward_hooks = OrderedDict()
self._forward_pre_hooks = OrderedDict()
self._state_dict_hooks = OrderedDict()
self._load_state_dict_pre_hooks = OrderedDict()
self._modules = OrderedDict()
self.training = True
属性解释:
_parameters:字典,保存用户直接设置的 Parameter
_modules:子 module,即子类构造函数中的内容
_buffers:缓存
_backward_hooks与_forward_hooks:钩子技术,用来提取中间变量
training:判断值来决定前向传播策略
方法定义:
def forward(self, *input):
raise NotImplementedError
没有实际内容,用于被子类的 forward() 方法覆盖
且 forward 方法在 __call__ 方法中被调用:
def __call__(self, *input, **kwargs):
for hook in self._forward_pre_hooks.values():
hook(self, input)
if torch._C._get_tracing_state():
result = self._slow_forward(*input, **kwargs)
else:
result = self.forward(*input, **kwargs)
...
...
实例展示
简单搭建:
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = nn.Linear(n_feature, n_hidden)
self.out = nn.Linear(n_hidden, n_output)
def forward(self, x):
x = F.relu(self.hidden(x))
x = self.out(x)
return x
Net 类继承了 torch 的 Module 和 __init__ 功能
hidden 是隐藏层线性输出
out 是输出层线性输出
打印出网络的结构:
>>> net = Net(n_feature=10, n_hidden=30, n_output=15)
>>> print(net)
Net(
(hidden): Linear(in_features=10, out_features=30, bias=True)
(out): Linear(in_features=30, out_features=15, bias=True)
)
来源:https://blog.csdn.net/weixin_44613063/article/details/90297299
标签:PyTorch,nn.Module
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
谈一谈bootstrap响应式布局
2023-08-22 20:17:39
![](https://img.aspxhome.com/file/2023/3/56053_0s.png)
DHTML+XML+ASP+CSS的树形目录
2008-10-24 14:29:00
腾讯网QQ首页诞生的艰辛历程
2008-11-06 11:05:00
![](https://img.aspxhome.com/file/UploadPic/200811/6/01-77s.jpg)
10分钟用Python快速搭建全文搜索引擎详解流程
2023-11-06 16:13:41
![](https://img.aspxhome.com/file/2023/1/67321_0s.png)
sqlserver索引的原理及索引建立的注意事项小结
2012-08-21 10:54:34
python类属性学习深入讲解
2021-03-25 06:05:34
![](https://img.aspxhome.com/file/2023/7/66747_0s.png)
Python监听剪切板实现方法代码实例
2023-11-10 13:48:32
python使用cartopy库绘制台风路径代码
2023-08-22 15:50:18
![](https://img.aspxhome.com/file/2023/3/70783_0s.jpg)
使用python怎样产生10个不同的随机数
2021-08-12 13:07:18
![](https://img.aspxhome.com/file/2023/7/67927_0s.png)
ASP在线升级类文件源码
2008-10-10 13:09:00
python optparse模块使用实例
2021-02-03 22:01:36
一段Asp301重定向过程代码
2010-05-04 16:38:00
python有几个版本
2021-09-12 00:44:30
Pygame实战练习之飞机大战游戏
2021-01-13 13:11:25
![](https://img.aspxhome.com/file/2023/3/72723_0s.gif)
如何定义记录集打开的游标类型?
2009-11-15 20:19:00
在Dreamweaver中自动设置网页的水平线颜色
2007-02-03 11:30:00
Golang实现http文件上传小功能的案例
2023-07-19 00:55:37
SQL进行排序、分组、统计的10个新技巧
2009-01-23 13:59:00
python使用turtle库绘制奥运五环
2021-06-21 04:22:44
![](https://img.aspxhome.com/file/2023/5/72855_0s.jpg)
python中as用法实例分析
2023-08-11 01:12:26