新建一个神经网络,方式一,基于 torch.nn.Sequential

更新日期: 2023-01-05 阅读次数: 1631 字数: 356 分类: AI

构建神经网络的两种方式

PyTorch 有两种构建神经网络的方式:

  • 简单粗暴式:使用 torch.nn.Sequential 类,初始化时,传入一系列操作 (operation)
  • 通用式:定义 torch.nn.Module 的子类

由于涉及的新概念非常多,所以拆分成两个笔记。这里就先了解一下第一种方式。

torch.nn.Sequential

https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html

CLASS torch.nn.Sequential(*args: Module)
CLASS torch.nn.Sequential(arg: OrderedDict[str, Module])

Sequential 的 forward 函数会自动将初始化参数中的 Module (模块)串联起来执行。 前一个 Module 的输出作为下一个 Module 的输入。

def forward(self, input):
	for module in self:
		input = module(input)
	return input

定义方式一

直接通过初始化参数

import torch
import torch. nn as nn
myNeuralNetwork = nn.Sequential(
	nn.Linear(3, 2),
	nn.ReLU(),
	nn.Linear(2, 1),
	nn.Sigmoid())

定义方式二

通过 add_module 添加模块

container = nn.Sequential()
begin_convol_layer = nn.Conv2d(input_channels=2, output_channels=12, kernel_size=2, stride=1, padding=1)
container.add_module("Conv1", begin_convol_layer)
relu1 = nn.ReLU(inplace=False)
container.add_module("Relu1", relu1)

nn.Linear 操作 (operation)

最常见的操作是 nn.Linear()

class torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)

https://pytorch.org/docs/stable/generated/torch.nn.Linear.html

Applies a linear transformation to the incoming data

即,对输入数据进行线性变换。

  • in_features (int) – size of each input sample
  • out_features (int) – size of each output sample

例如,上图中的神经网络中的第一步:

  • in_features 为 3
  • out_features 为 2

第二步:

  • in_features 为 2
  • out_features 为 1

Module 与 Model 的区别

  • Module 是模块
  • Model 是模型

ReLU

全称是 Rectified Linear Unit。

PyTorch 内置了 ReLU:

nn.ReLU()

tags: pytorch

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式