pytorch基础3-构建模型层

专题链接:https://blog.csdn.net/qq_33345365/category_12591348.html

本教程翻译自微软教程:https://learn.microsoft.com/en-us/training/paths/pytorch-fundamentals/

初次编辑:2024/3/2;最后编辑:2024/3/3


本教程第一篇:介绍pytorch基础和张量操作

本教程第二篇,介绍了数据集与归一化

本教程介绍构建模型层的基本操作。

另外本人还有pytorch CV相关的教程,见专题:

https://blog.csdn.net/qq_33345365/category_12578430.html


构建模型层


什么是神经网络

神经网络是由神经元(neurons)通过层连接而成的集合。每个神经元是一个小型计算单元,执行简单的计算以共同解决问题。神经元分布在三种类型的层中:输入层、隐藏层和输出层。隐藏层和输出层包含多个神经元。神经网络模仿人类大脑处理信息的方式。

一个层包含多个神经元,一个神经网络包含多层,

神经网络的组件

  • **激活函数(activation function)**决定神经元是否应该被激活。神经网络中的计算包括应用激活函数。如果一个神经元被激活,那么意味着输入是重要的。有不同类型的激活函数,选择使用哪种激活函数取决于您想要的输出是什么。激活函数的另一个重要作用是为模型添加非线性。

    • Binary:输出节点被设置为1(如果函数结果为正)或0(如果函数结果为零或负)。 f ( x ) = { 0 , if  x < 0 1 , if  x ≥ 0 f(x)= {\small \begin{cases} 0, & \text{if } x < 0\\ 1, & \text{if } x\geq 0\\ \end{cases}} f(x)={0,1,if x<0if x0
    • Sigmoid:用于预测输出节点的概率在0到1之间。 f ( x ) = 1 1 + e − x f(x) = {\large \frac{1}{1+e^{-x}}} f(x)=1+ex1
    • Tanh用于预测输出节点是否在1和-1之间,适用于分类用例。 f ( x ) = e x − e − x e x + e − x f(x) = {\large \frac{e^{x} - e^{-x}}{e^{x} + e^{-x}}} f(x)=ex+exexex
    • ReLU(修正线性激活函数)用于将输出节点设置为0(如果函数结果为负)并保持结果值(如果结果为正)。 f ( x ) = { 0 , if  x < 0 x , if  x ≥ 0 f(x)= {\small \begin{cases} 0, & \text{if } x < 0\\ x, & \text{if } x\geq 0\\ \end{cases}} f(x)={0,x,if x<0if x0
  • **权重(Weight)**影响网络输出与预期输出值之间的接近程度。当输入进入神经元时,它会乘以一个权重值,得到的输出结果要么被观察到,要么传递到神经网络中的下一层。

  • 一个层中所有神经元的权重被组织成一个张量。

  • 偏差构成了激活函数输出与其预期输出之间的差异。低偏差表明网络对输出形式做出了更多假设,而高偏差值则表示对输出形式做出了较少的假设。

可以说,具有权重 W W W和偏差 b b b的神经网络层的输出 y y y是输入乘以权重加上偏差的总和。$x = \sum{(weights * inputs) + bias} ,其中 ,其中 ,其中f(x)$是激活函数。

构建神经网络

神经网络由层和模块组成,这些模块对数据执行操作。torch.nn命名空间提供了构建自己的神经网络所需的所有构建块。PyTorch中的每个模块都是nn.Module的子类。神经网络本身是一个模块,它由其他模块(层)组成。这种嵌套结构使得可以轻松构建和管理复杂的架构。

在接下来的部分中,将构建一个神经网络来对FashionMNIST数据集中的图像进行分类。下面是需要使用到的类:

import os
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

取得训练的硬件设备

我们希望能够在类似GPU这样的硬件加速器上训练我们的模型,如果有的话。让我们检查一下torch.cuda是否可用;如果不可用,我们将继续使用CPU。

device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Using {} device'.format(device))

定义类

我们通过子类化 nn.Module 来定义我们的神经网络,并在 __init__ 中初始化神经网络层。每个 nn.Module 子类在 forward 方法中实现对输入数据的操作。

我们的神经网络由以下部分组成:

  • 输入层具有 28x28 或 784 个特征/像素。
  • 第一个线性模块接受 784 个特征的输入,并将其转换为具有 512 个特征的隐藏层。
  • 在转换中应用 ReLU 激活函数。
  • 第二个线性模块接受来自第一个隐藏层的 512 个特征作为输入,并将其转换为具有 512 个特征的下一个隐藏层。
  • 在转换中应用 ReLU 激活函数。
  • 第三个线性模块接受来自第二个隐藏层的 512 个特征作为输入,并将这些特征转换为具有 10 个特征的输出层,这是类别的数量。
  • 在转换中应用 ReLU 激活函数。
class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10),
            nn.ReLU()
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

下面,创建NeuralNetwork的实例,并将其移到device上并打印结构。

model = NeuralNetwork().to(device)
print(model)

输出为:

NeuralNetwork(
  (flatten): Flatten()
  (linear_relu_stack): Sequential(
    (0): Linear(in_features=784, out_features=512, bias=True)
    (1): ReLU()
    (2): Linear(in_features=512, out_features=512, bias=True)
    (3): ReLU()
    (4): Linear(in_features=512, out_features=10, bias=True)
    (5): ReLU()
  )
)

要使用模型,需要将输入数据传递给它。这将执行模型的forward,以及一些背景操作(background operation)。但是,请不要直接调用model.forward()!在输入上调用模型会返回一个具有每个类别的原始预测值的10维张量。

模型的背景操作是指在执行前向传播(forward pass)时发生的内部计算或处理步骤。这些操作可能包括参数初始化、梯度计算、损失函数的计算、优化器的更新等。这些操作在模型的forward方法内部进行,通常是在将输入数据传递给模型时自动执行的,而不需要用户显式调用。这些操作的目的是在训练过程中优化模型参数,使其能够更好地拟合数据并提高性能。

我们通过将其传递给nn.Softmax的实例来获取预测密度。

X = torch.rand(1, 28, 28, device=device)
logits = model(X) 
pred_probab = nn.Softmax(dim=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")

输出是:

Predicted class: tensor([2], device='cuda:0')

权重与偏置

nn.Linear模块随机初始化每一层的weightbias并在内部将值存储在张量中。

print(f"First Linear weights: {model.linear_relu_stack[0].weight} \n")
print(f"First Linear biases: {model.linear_relu_stack[0].bias} \n")

模型层

让我们分解一下FashionMNIST模型中的层。为了说明这一点,我们将取一个大小为28x28的样本小批量,其中包含3张图像,然后看看当我们将其通过网络传递时会发生什么。

input_image = torch.rand(3,28,28)
print(input_image.size())

输出是:

torch.Size([3, 28, 28])

nn.Flatten

我们初始化nn.Flatten层,将每个2D的28x28图像转换为一个连续的包含784个像素值的数组,即,小批量维度(在dim=0处)保持不变。每个像素都传递到神经网络的输入层。

flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())

输出:

torch.Size([3, 784])

nn.Linear

线性层是一个模块,它使用其存储的权重和偏置对输入进行线性变换。输入层中每个像素的灰度值将连接到隐藏层中的神经元进行计算。用于变换的计算是 w e i g h t ∗ i n p u t + b i a s {{weight * input + bias}} weightinput+bias

layer1 = nn.Linear(in_features=28*28, out_features=20)
hidden1 = layer1(flat_image)
print(hidden1.size())

输出:

torch.Size([3, 20])

nn.ReLU

非线性激活函数是在模型的输入和输出之间创建复杂映射的关键。它们被应用在线性变换之后,引入非线性(nonlinearity),帮助神经网络学习各种现象。在这个模型中,我们在线性层之间使用nn.ReLU,但还有其他激活函数可以引入非线性到模型中。

ReLU激活函数接收线性层计算的输出,并用零替换负值。

线性输出: ${ x = {weight * input + bias}} $​.
ReLU:

f ( x ) = { 0 , if  x < 0 x , if  x ≥ 0 f(x)=\begin{cases} 0, & \text{if } x < 0\\ x, & \text{if } x\geq 0\\ \end{cases} f(x)={0,x,if x<0if x0

print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")

输出:

Before ReLU: tensor([[ 0.2190,  0.1448, -0.5783,  0.1782, -0.4481, -0.2782, -0.5680,  0.1347,
          0.1092, -0.7941, -0.2273, -0.4437,  0.0661,  0.2095,  0.1291, -0.4690,
          0.0358,  0.3173, -0.0259, -0.4028],
        [-0.3531,  0.2385, -0.3172, -0.4717, -0.0382, -0.2066, -0.3859,  0.2607,
          0.3626, -0.4838, -0.2132, -0.7623, -0.2285,  0.2409, -0.2195, -0.4452,
         -0.0609,  0.4035, -0.4889, -0.4500],
        [-0.3651, -0.1240, -0.3222, -0.1072, -0.0112, -0.0397, -0.4105, -0.0233,
         -0.0342, -0.5680, -0.4816, -0.8085, -0.3945, -0.0472,  0.0247, -0.3605,
         -0.0347,  0.1192, -0.2763,  0.1447]], grad_fn=<AddmmBackward>)


After ReLU: tensor([[0.2190, 0.1448, 0.0000, 0.1782, 0.0000, 0.0000, 0.0000, 0.1347, 0.1092,
         0.0000, 0.0000, 0.0000, 0.0661, 0.2095, 0.1291, 0.0000, 0.0358, 0.3173,
         0.0000, 0.0000],
        [0.0000, 0.2385, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.2607, 0.3626,
         0.0000, 0.0000, 0.0000, 0.0000, 0.2409, 0.0000, 0.0000, 0.0000, 0.4035,
         0.0000, 0.0000],
        [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
         0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0247, 0.0000, 0.0000, 0.1192,
         0.0000, 0.1447]], grad_fn=<ReluBackward0>)

nn.Sequential

nn.Sequential 是一个有序的模块容器。数据按照它们定义的顺序通过所有模块。您可以使用顺序容器来组合一个快速网络,如下所示seq_modules

seq_modules = nn.Sequential(
    flatten,
    layer1,
    nn.ReLU(),
    nn.Linear(20, 10)
)
input_image = torch.rand(3,28,28)
logits = seq_modules(input_image)

nn.Softmax

神经网络的最后一个线性层返回logits(在[-infty, infty]范围内的原始值),这些值被传递给nn.Softmax模块。Softmax激活函数用于计算神经网络输出的概率。它只用于神经网络的输出层。结果被缩放到[0,1]的值,表示模型对每个类别的预测密度。dim参数指示结果值必须在哪个维度上求和为1。具有最高概率的节点预测所需的输出。

softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)

模型参数

神经网络中的许多层都是参数化的,即,这些层具有关联的权重和偏置,在训练期间进行优化。子类化nn.Module会自动跟踪模型对象内部定义的所有字段,并使用模型的parameters()named_parameters()方法使所有参数可访问。

在这个例子中,我们遍历每个参数,并打印其大小和值的预览。

print("Model structure: ", model, "\n\n")

for name, param in model.named_parameters():
    print(f"Layer: {name} | Size: {param.size()} | Values : {param[:2]} \n")

输出是:

Model structure:  NeuralNetwork(
  (flatten): Flatten()
  (linear_relu_stack): Sequential(
    (0): Linear(in_features=784, out_features=512, bias=True)
    (1): ReLU()
    (2): Linear(in_features=512, out_features=512, bias=True)
    (3): ReLU()
    (4): Linear(in_features=512, out_features=10, bias=True)
    (5): ReLU()
  )
) 


Layer: linear_relu_stack.0.weight | Size: torch.Size([512, 784]) | Values : tensor([[-0.0320,  0.0326, -0.0032,  ..., -0.0236, -0.0025, -0.0175],
        [ 0.0180,  0.0271, -0.0314,  ..., -0.0094, -0.0170, -0.0257]],
       device='cuda:0', grad_fn=<SliceBackward>) 

Layer: linear_relu_stack.0.bias | Size: torch.Size([512]) | Values : tensor([-0.0134,  0.0036], device='cuda:0', grad_fn=<SliceBackward>) 

Layer: linear_relu_stack.2.weight | Size: torch.Size([512, 512]) | Values : tensor([[-0.0262,  0.0072, -0.0348,  ..., -0.0374,  0.0345,  0.0374],
        [ 0.0439, -0.0101,  0.0218,  ..., -0.0419,  0.0212, -0.0081]],
       device='cuda:0', grad_fn=<SliceBackward>) 

Layer: linear_relu_stack.2.bias | Size: torch.Size([512]) | Values : tensor([ 0.0131, -0.0289], device='cuda:0', grad_fn=<SliceBackward>) 

Layer: linear_relu_stack.4.weight | Size: torch.Size([10, 512]) | Values : tensor([[ 0.0376, -0.0359, -0.0329,  ..., -0.0057,  0.0040,  0.0307],
        [-0.0196, -0.0440,  0.0250,  ...,  0.0335,  0.0024, -0.0207]],
       device='cuda:0', grad_fn=<SliceBackward>) 

Layer: linear_relu_stack.4.bias | Size: torch.Size([10]) | Values : tensor([-0.0287,  0.0321], device='cuda:0', grad_fn=<SliceBackward>) 

代码汇总

import os
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Using {} device'.format(device))


class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28 * 28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10),
            nn.ReLU()
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits


model = NeuralNetwork().to(device)
print(model)

X = torch.rand(1, 28, 28, device=device)
logits = model(X)
pred_probab = nn.Softmax(dim=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")

print(f"First Linear weights: {model.linear_relu_stack[0].weight} \n")

print(f"First Linear biases: {model.linear_relu_stack[0].bias} \n")

input_image = torch.rand(3, 28, 28)
print(input_image.size())

flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())

layer1 = nn.Linear(in_features=28 * 28, out_features=20)
hidden1 = layer1(flat_image)
print(hidden1.size())

print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")

seq_modules = nn.Sequential(
    flatten,
    layer1,
    nn.ReLU(),
    nn.Linear(20, 10)
)
input_image = torch.rand(3, 28, 28)
logits = seq_modules(input_image)

softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)

print("Model structure: ", model, "\n\n")

for name, param in model.named_parameters():
    print(f"Layer: {name} | Size: {param.size()} | Values : {param[:2]} \n")
  • 13
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

whyte王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值