神经网络的基本骨架-nn.Module的使用
网络的搭建,以不同的案例演示不同的效果
左侧可以看到Python的API,就是不同的包,提供了不同的工具
我们关于神经网络的工具主要在torch.nn里面,nn主要来自neural network的缩写
torch.nn分布不同的类别,Containers主要给神经网络定义了一些骨架、结构,往这些结构中添加一些不同的内容我们就可以组成神经网络,这一节学习神经网络的一个基本搭建
后面的都是需要往骨架中填充的东西:
Convolution Layers(卷积层)
Pooling layers(池化层)
Padding Layers(填充层)
Non-linear Activations (weighted sum, nonlinearity)(非线性激活(加权和、非线性))
Non-linear Activations (other)(非线性激活(其他))
Normalization Layers(标准化层)
这些都是组成卷积神经网络的核心的操作部分
Containers中有6个模块
Module--Base class for all neural network modules.(所有神经网络模块的基类)
常见的神经网络必须从这个类中继承,比如下面这个例子:
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = nn.Conv2d(1, 20, 5)
self.conv2 = nn.Conv2d(20, 20, 5)
def forward(self, x):
x = F.relu(self.conv1(x))
return F.relu(self.conv2(x))
Module是Model的父类,定义了两个函数就是进行了一些修改
input->forward->output,前向传播,还有一个反向传播
输入x->卷积->非线性->卷积->非线性->返回作为模型的输出
forward(*input)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
forward主要定义了一些计算,在所有子类中进行重写
所以说使用这个Module的时候就使用这个模板,自己定义模型名,继承这个类,然后在init函数和forward函数中写一些必要的条件
写的时候可以自己写,也可以生成->重写方法
import torch
from torch import nn
class NN_Module(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input):
output = input + 1
return output
nn_Module = NN_Module()
x = torch.tensor(1.0)
output = nn_Module(x)
print(output)
返回tensor(2.)
debug中选择单步执行可以查看变量的变化过程
之后讲解卷积层,解释它的效果是如何
原始资料地址:
神经网络的基本骨架-nn.Module的使用
如有侵权联系删除 仅供学习交流使用