Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

浅析PyTorch中nn.Module的使用

来源:中文源码网    浏览:346 次    日期:2024-04-26 00:42:16
【下载文档:  浅析PyTorch中nn.Module的使用.txt 】


浅析PyTorch中nn.Module的使用
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)
)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持中文源码网。

相关内容