注意
单击此处下载完整的示例代码
简介 ||张量 ||Autograd ||建筑模型 ||TensorBoard 支持 ||训练模型 ||模型理解
使用 PyTorch 构建模型¶
创建时间: 2021年11月30日 |上次更新时间:2024 年 10 月 15 日 |上次验证: Nov 05, 2024
请跟随下面的视频或在 youtube 上观看。
torch.nn.Module
和torch.nn.Parameter
¶
在本视频中,我们将讨论 PyTorch 提供的一些工具 可用于构建深度学习网络。
除了 之外,我们在本视频中讨论的类都是
的子类。这就是 PyTorch 基类的含义
封装特定于 PyTorch 模型及其
组件。Parameter
torch.nn.Module
的一个重要行为是注册参数。
如果特定子类具有学习权重,则这些权重
表示为 的实例。该类是 的子类 ,具有
当它们被分配为 的属性 时,它们将被添加到
该 modules 参数的列表。可以访问这些参数
通过类上的方法。torch.nn.Module
Module
torch.nn.Parameter
Parameter
torch.Tensor
Module
parameters()
Module
举个简单的例子,这里有一个非常简单的模型,有两个线性层 以及激活函数。我们将创建一个实例并要求它 报告其参数:
import torch
class TinyModel(torch.nn.Module):
def __init__(self):
super(TinyModel, self).__init__()
self.linear1 = torch.nn.Linear(100, 200)
self.activation = torch.nn.ReLU()
self.linear2 = torch.nn.Linear(200, 10)
self.softmax = torch.nn.Softmax()
def forward(self, x):
x = self.linear1(x)
x = self.activation(x)
x = self.linear2(x)
x = self.softmax(x)
return x
tinymodel = TinyModel()
print('The model:')
print(tinymodel)
print('\n\nJust one layer:')
print(tinymodel.linear2)
print('\n\nModel params:')
for param in tinymodel.parameters():
print(param)
print('\n\nLayer params:')
for param in tinymodel.linear2.parameters():
print(param)
The model:
TinyModel(
(linear1): Linear(in_features=100, out_features=200, bias=True)
(activation): ReLU()
(linear2): Linear(in_features=200, out_features=10, bias=True)
(softmax): Softmax(dim=None)
)
Just one layer:
Linear(in_features=200, out_features=10, bias=True)
Model params:
Parameter containing:
tensor([[ 0.0765, 0.0830, -0.0234, ..., -0.0337, -0.0355, -0.0968],
[-0.0573, 0.0250, -0.0132, ..., -0.0060, 0.0240, 0.0280],
[-0.0908, -0.0369, 0.0842, ..., -0.0078, -0.0333, -0.0324],
...,
[-0.0273, -0.0162, -0.0878, ..., 0.0451, 0.0297, -0.0722],
[ 0.0833, -0.0874, -0.0020, ..., -0.0215, 0.0356, 0.0405],
[-0.0637, 0.0190, -0.0571, ..., -0.0874, 0.0176, 0.0712]],
requires_grad=True)
Parameter containing:
tensor([ 0.0304, -0.0758, -0.0549, -0.0893, -0.0809, -0.0804, -0.0079, -0.0413,
-0.0968, 0.0888, 0.0239, -0.0659, -0.0560, -0.0060, 0.0660, -0.0319,
-0.0370, 0.0633, -0.0143, -0.0360, 0.0670, -0.0804, 0.0265, -0.0870,
0.0039, -0.0174, -0.0680, -0.0531, 0.0643, 0.0794, 0.0209, 0.0419,
0.0562, -0.0173, -0.0055, 0.0813, 0.0613, -0.0379, 0.0228, 0.0304,
-0.0354, 0.0609, -0.0398, 0.0410, 0.0564, -0.0101, -0.0790, -0.0824,
-0.0126, 0.0557, 0.0900, 0.0597, 0.0062, -0.0108, 0.0112, -0.0358,
-0.0203, 0.0566, -0.0816, -0.0633, -0.0266, -0.0624, -0.0746, 0.0492,
0.0450, 0.0530, -0.0706, 0.0308, 0.0533, 0.0202, -0.0469, -0.0448,
0.0548, 0.0331, 0.0257, -0.0764, -0.0892, 0.0783, 0.0062, 0.0844,
-0.0959, -0.0468, -0.0926, 0.0925, 0.0147, 0.0391, 0.0765, 0.0059,
0.0216, -0.0724, 0.0108, 0.0701, -0.0147, -0.0693, -0.0517, 0.0029,
0.0661, 0.0086, -0.0574, 0.0084, -0.0324, 0.0056, 0.0626, -0.0833,
-0.0271, -0.0526, 0.0842, -0.0840, -0.0234, -0.0898, -0.0710, -0.0399,
0.0183, -0.0883, -0.0102, -0.0545, 0.0706, -0.0646, -0.0841, -0.0095,
-0.0823, -0.0385, 0.0327, -0.0810, -0.0404, 0.0570, 0.0740, 0.0829,
0.0845, 0.0817, -0.0239, -0.0444, -0.0221, 0.0216, 0.0103, -0.0631,
0.0831, -0.0273, 0.0756, 0.0022, 0.0407, 0.0072, 0.0374, -0.0608,
0.0424, -0.0585, 0.0505, -0.0455, 0.0268, -0.0950, -0.0642, 0.0843,
0.0760, -0.0889, -0.0617, -0.0916, 0.0102, -0.0269, -0.0011, 0.0318,
0.0278, -0.0160, 0.0159, -0.0817, 0.0768, -0.0876, -0.0524, -0.0332,
-0.0583, 0.0053, 0.0503, -0.0342, -0.0319, -0.0562, 0.0376, -0.0696,
0.0735, 0.0222, -0.0775, -0.0072, 0.0294, 0.0994, -0.0355, -0.0809,
-0.0539, 0.0245, 0.0670, 0.0032, 0.0891, -0.0694, -0.0994, 0.0126,
0.0629, 0.0936, 0.0058, -0.0073, 0.0498, 0.0616, -0.0912, -0.0490],
requires_grad=True)
Parameter containing:
tensor([[ 0.0504, -0.0203, -0.0573, ..., 0.0253, 0.0642, -0.0088],
[-0.0078, -0.0608, -0.0626, ..., -0.0350, -0.0028, -0.0634],
[-0.0317, -0.0202, -0.0593, ..., -0.0280, 0.0571, -0.0114],
...,
[ 0.0582, -0.0471, -0.0236, ..., 0.0273, 0.0673, 0.0555],
[ 0.0258, -0.0706, 0.0315, ..., -0.0663, -0.0133, 0.0078],
[-0.0062, 0.0544, -0.0280, ..., -0.0303, -0.0326, -0.0462]],
requires_grad=True)
Parameter containing:
tensor([ 0.0385, -0.0116, 0.0703, 0.0407, -0.0346, -0.0178, 0.0308, -0.0502,
0.0616, 0.0114], requires_grad=True)
Layer params:
Parameter containing:
tensor([[ 0.0504, -0.0203, -0.0573, ..., 0.0253, 0.0642, -0.0088],
[-0.0078, -0.0608, -0.0626, ..., -0.0350, -0.0028, -0.0634],
[-0.0317, -0.0202, -0.0593, ..., -0.0280, 0.0571, -0.0114],
...,
[ 0.0582, -0.0471, -0.0236, ..., 0.0273, 0.0673, 0.0555],
[ 0.0258, -0.0706, 0.0315, ..., -0.0663, -0.0133, 0.0078],
[-0.0062, 0.0544, -0.0280, ..., -0.0303, -0.0326, -0.0462]],
requires_grad=True)
Parameter containing:
tensor([ 0.0385, -0.0116, 0.0703, 0.0407, -0.0346, -0.0178, 0.0308, -0.0502,
0.0616, 0.0114], requires_grad=True)
这显示了 PyTorch 模型的基本结构:有一个方法可以定义
model 和完成计算的方法。注意
我们可以打印模型或其任何子模块来了解
它的结构。__init__()
forward()
常见图层类型¶
线性层¶
神经网络层的最基本类型是线性或完全 connected 层。在这个层中,每个输入都会影响每个 output 的 Layer,以达到图层权重指定的程度。如果 模型有 m 个输入和 n 个输出,权重将是一个 M x N 矩阵。例如:
lin = torch.nn.Linear(3, 2)
x = torch.rand(1, 3)
print('Input:')
print(x)
print('\n\nWeight and Bias parameters:')
for param in lin.parameters():
print(param)
y = lin(x)
print('\n\nOutput:')
print(y)
Input:
tensor([[0.8790, 0.9774, 0.2547]])
Weight and Bias parameters:
Parameter containing:
tensor([[ 0.1656, 0.4969, -0.4972],
[-0.2035, -0.2579, -0.3780]], requires_grad=True)
Parameter containing:
tensor([0.3768, 0.3781], requires_grad=True)
Output:
tensor([[ 0.8814, -0.1492]], grad_fn=<AddmmBackward0>)
如果将矩阵乘以线性层的
weights 并添加偏差,您会发现您得到了 output vector .x
y
另一个需要注意的重要功能:当我们检查我们的
层中,它将自身报告为一个 (其中
是 ) 的子类,并告诉我们它正在跟踪
使用 autograd 的渐变。这是不同于 的默认行为。lin.weight
Parameter
Tensor
Parameter
Tensor
线性层在深度学习模型中广泛使用。最 常见位置是 Classifier Models,这将 通常在末尾有一个或多个线性层,其中最后一层 将有 n 个输出,其中 n 是分类器的类数 地址。
卷积层¶
构建卷积层是为了处理具有高度 空间相关性。它们非常常用于计算机视觉、 其中,它们检测将 Compose 更高级别的功能。它们也会在其他上下文中弹出 - 例如, 在 NLP 应用程序中,单词的直接上下文(即 序列中附近的其他单词)可能会影响 句。
我们在前面的视频中看到了 LeNet5 中的卷积层:
import torch.functional as F
class LeNet(torch.nn.Module):
def __init__(self):
super(LeNet, self).__init__()
# 1 input image channel (black & white), 6 output channels, 5x5 square convolution
# kernel
self.conv1 = torch.nn.Conv2d(1, 6, 5)
self.conv2 = torch.nn.Conv2d(6, 16, 3)
# an affine operation: y = Wx + b
self.fc1 = torch.nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
self.fc2 = torch.nn.Linear(120, 84)
self.fc3 = torch.nn.Linear(84, 10)
def forward(self, x):
# Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# If the size is a square you can only specify a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
让我们分解一下这个卷积层中发生的事情
型。以 开头 :conv1
LeNet5 旨在接收 1x32x32 的黑白图像。第一个 参数是 input channels。这里,它是 1。如果我们构建这个模型是为了 看看 3 色通道,它会是 3。
卷积层就像一个扫描图像的窗口, 寻找它识别的模式。这些模式称为特征,卷积层的参数之一是 我们希望它学习的功能数量。这是第二个 argument 是输出特征的数量。这里 我们要求我们的 Layer 学习 6 个功能。
就在上面,我将卷积层比作一个窗口 - 但是 窗户很大吗?第三个参数是 window 或 kernel 大小。这里,“5” 表示我们选择了 5x5 内核。(如果您想要 kernel 的 height 与 width 不同,你可以为 这个参数 - 例如,获取 3x5 卷积内核。
(3, 5)
卷积层的输出是一个激活图 - 一个空间
表示 Importing Tensor 中存在的特征。 将得到 6x28x28 的输出张量;6 是
features,28 是我们地图的高度和宽度。(28 来自
事实上,当扫描 32 像素行上的 5 像素窗口时,存在
只有 28 个有效位置。conv1
然后,我们通过 ReLU 激活传递卷积的输出 函数(稍后会详细介绍激活函数),然后通过 MAX pooling 层。最大池化图层采用彼此靠近的要素 激活映射并将它们分组在一起。它通过减少 张量,将输出中的每 2x2 组单元格合并为单个 单元格,并为该单元格分配 4 个单元格的最大值 进入它。这为我们提供了较低分辨率版本的激活地图 尺寸为 6x14x14。
我们的下一个卷积层 需要 6 个输入通道
(对应于第一层寻求的 6 个特征),有 16 个
output channels 和 3x3 内核。它发出一个 16x12x12 的激活
map,该图层再次被 Max pooling 层减少到 16x6x6。之前
将此输出传递给线性图层,它将被重塑为 16 * 6 *
6 = 576 个元素的向量,供下一层使用。conv2
有用于寻址 1D 、 2D 和 3D 张量的卷积层。 conv 层还有更多可选参数 构造函数,包括 stride length(例如,仅每秒扫描一次或 中,填充(以便您可以扫描到 边)等等。有关更多信息,请参阅文档。
循环层¶
递归神经网络(或 RNN)用于顺序数据 - 从科学仪器的时间序列测量到 DNA 核苷酸的自然语言句子。RNN 通过以下方式实现此目的 维护一个隐藏状态,它充当了它 到目前为止在序列中已经看到。
RNN 层的内部结构 - 或其变体 LSTM (长 短期记忆)和 GRU (门控循环单元) - 是中等的 复杂且超出了本视频的范围,但我们将向您展示哪个 看起来就像在操作中使用基于 LSTM 的词性标记器(一种 告诉您单词是否为名词、动词等的分类器):
class LSTMTagger(torch.nn.Module):
def __init__(self, embedding_dim, hidden_dim, vocab_size, tagset_size):
super(LSTMTagger, self).__init__()
self.hidden_dim = hidden_dim
self.word_embeddings = torch.nn.Embedding(vocab_size, embedding_dim)
# The LSTM takes word embeddings as inputs, and outputs hidden states
# with dimensionality hidden_dim.
self.lstm = torch.nn.LSTM(embedding_dim, hidden_dim)
# The linear layer that maps from hidden state space to tag space
self.hidden2tag = torch.nn.Linear(hidden_dim, tagset_size)
def forward(self, sentence):
embeds = self.word_embeddings(sentence)
lstm_out, _ = self.lstm(embeds.view(len(sentence), 1, -1))
tag_space = self.hidden2tag(lstm_out.view(len(sentence), -1))
tag_scores = F.log_softmax(tag_space, dim=1)
return tag_scores
构造函数有四个参数:
vocab_size
是输入词汇表中的单词数。每 word 是 -维空间中的 one-hot 向量(或单位向量)。vocab_size
tagset_size
是输出集中的标签数。embedding_dim
是 词汇。嵌入将词汇表映射到低维 space 中,其中具有相似含义的单词在 空间。hidden_dim
是 LSTM 的内存大小。
输入将是一个句子,其中单词表示为
one-hot 向量。然后,嵌入层会将这些映射到 -维空间。LSTM 采用以下序列
嵌入并迭代它,并执行长度为 .最终的线性层充当分类器;应用于最终图层的输出将转换输出
转换为给定单词映射的一组标准化估计概率
添加到给定的标签中。embedding_dim
hidden_dim
log_softmax()
如果您想了解此网络的实际应用,请查看序列 模型和 LSTM pytorch.org 上的 Networks 教程。
变形金刚¶
变压器是已经接管该州的多用途网络
使用 BERT 等模型进行 NLP 的艺术。变压器的讨论
体系结构超出了本视频的范围,但 PyTorch 有一个类,允许您定义整体参数
transformer 模型 - attention heads 的数量,number of a transformer model - 注意力头的数量,number of a
编码器和解码器层,dropout和激活功能等(你
甚至可以从这个 class 构建 BERT 模型,使用正确的
参数!该类还具有
封装各个组件 (, ) 和子组件 (, )。有关详细信息,请查看有关 transformer 类的文档。Transformer
torch.nn.Transformer
TransformerEncoder
TransformerDecoder
TransformerEncoderLayer
TransformerDecoderLayer
其他图层和功能¶
数据操作层¶
还有其他层类型在模型中执行重要功能, 但不要自己参与学习过程。
最大池化(及其孪生体,最小池化)通过组合 单元格,并将输入单元格的最大值分配给输出 cell (我们看到了这个)。例如:
my_tensor = torch.rand(1, 6, 6)
print(my_tensor)
maxpool_layer = torch.nn.MaxPool2d(3)
print(maxpool_layer(my_tensor))
tensor([[[0.5036, 0.6285, 0.3460, 0.7817, 0.9876, 0.0074],
[0.3969, 0.7950, 0.1449, 0.4110, 0.8216, 0.6235],
[0.2347, 0.3741, 0.4997, 0.9737, 0.1741, 0.4616],
[0.3962, 0.9970, 0.8778, 0.4292, 0.2772, 0.9926],
[0.4406, 0.3624, 0.8960, 0.6484, 0.5544, 0.9501],
[0.2489, 0.8971, 0.7499, 0.1803, 0.9571, 0.6733]]])
tensor([[[0.7950, 0.9876],
[0.9970, 0.9926]]])
如果你仔细查看上面的值,你会发现每个 maxpooled 输出中的值是 6x6 输入。
归一化层将一个层的输出重新居中并归一化 在把它喂给另一个人之前。居中和缩放中间体 张量具有许多有益的效果,例如让您使用 更高的学习率,而不会爆炸/消失梯度。
my_tensor = torch.rand(1, 4, 4) * 20 + 5
print(my_tensor)
print(my_tensor.mean())
norm_layer = torch.nn.BatchNorm1d(4)
normed_tensor = norm_layer(my_tensor)
print(normed_tensor)
print(normed_tensor.mean())
tensor([[[ 7.7375, 23.5649, 6.8452, 16.3517],
[19.5792, 20.3254, 6.1930, 23.7576],
[23.7554, 20.8565, 18.4241, 8.5742],
[22.5100, 15.6154, 13.5698, 11.8411]]])
tensor(16.2188)
tensor([[[-0.8614, 1.4543, -0.9919, 0.3990],
[ 0.3160, 0.4274, -1.6834, 0.9400],
[ 1.0256, 0.5176, 0.0914, -1.6346],
[ 1.6352, -0.0663, -0.5711, -0.9978]]],
grad_fn=<NativeBatchNormBackward0>)
tensor(3.3528e-08, grad_fn=<MeanBackward0>)
运行上面的单元格,我们添加了一个较大的缩放因子和 offset 到
输入张量;您应该会看到输入张量的
在 15 附近。通过规范化运行它之后
层中,您可以看到这些值更小,并且分组在零附近
- 事实上,平均值应该非常小 (> 1e-8)。mean()
这是有益的,因为许多激活函数(下面讨论) 在 0 附近具有最强的梯度,但有时会受到 将它们驱赶到很远的输入的梯度消失或爆炸 从零开始。使数据以最陡区域为中心 梯度往往意味着更快、更好的学习和更高的可行性 学习率。
Dropout layers 是一种鼓励模型使用稀疏表示的工具,也就是说,推动它使用更少的数据进行推理。
Dropout 层的工作原理是在训练期间随机设置输入张量的部分 - Dropout 层始终处于关闭状态以进行推理。 这会强制模型针对此掩码或缩减的数据集进行学习。 例如:
my_tensor = torch.rand(1, 4, 4)
dropout = torch.nn.Dropout(p=0.4)
print(dropout(my_tensor))
print(dropout(my_tensor))
tensor([[[0.8869, 0.6595, 0.2098, 0.0000],
[0.5379, 0.0000, 0.0000, 0.0000],
[0.1950, 0.2424, 1.3319, 0.5738],
[0.5676, 0.8335, 0.0000, 0.2928]]])
tensor([[[0.8869, 0.6595, 0.2098, 0.2878],
[0.5379, 0.0000, 0.4029, 0.0000],
[0.0000, 0.2424, 1.3319, 0.5738],
[0.0000, 0.8335, 0.9647, 0.0000]]])
在上面,您可以看到 dropout 对样本张量的影响。您可以使用
可选参数,用于设置单个
体重下降;如果不这样做,则默认为 0.5。p
激活函数¶
激活函数使深度学习成为可能。神经网络是 实际上是一个程序 - 具有许多参数 - 模拟数学 功能。如果我们所做的只是按层权重划分多个张量 反复地,我们只能模拟线性函数;此外,还有 没有意义拥有多个层,就像整个网络一样 reduce 可以简化为单个矩阵乘法。在层之间插入非线性激活函数可以允许深度 学习模型来模拟任何函数,而不仅仅是线性函数。
torch.nn.Module
包含封装所有主要
激活函数,包括 ReLU 及其许多变体,Tanh、
Hardtanh、sigmoid 等。它还包括其他功能,例如
Softmax,这在模型的输出阶段最有用。
损失函数¶
损失函数告诉我们模型的预测与正确的预测相差多远 答。PyTorch 包含多种损失函数,包括常见的 MSE(均方误差 = L2 范数)、交叉熵损失和负 似然损失(对分类器有用)等。
脚本总运行时间:(0 分 0.032 秒)