gpt4 book ai didi

python - 使用 Pytorch 进行深度学习 : understanding the neural network example

转载 作者:行者123 更新时间:2023-12-02 06:33:00 24 4
gpt4 key购买 nike

我正在阅读 Pytorch documentation我对所介绍的神经网络有几个问题。该文档定义了以下网络:

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 3x3 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 3)
self.conv2 = nn.Conv2d(6, 16, 3)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
self.fc2 = nn.Linear(120, 84)
self.fc3 = 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

现发表如下声明:

让我们尝试随机的 32x32 输入。注意:该网络 (LeNet) 的预期输入大小为 32x32。要在 MNIST 数据集上使用此网络,请将数据集中的图像大小调整为 32x32。

问题 1:为什么图像需要为 32x32(我假设这意味着 32 像素 x 32)?

第一个卷积将六个内核应用于图像,每个内核都是 3x3。这意味着,如果输入 channel 为 32x32,则六个输出 channel 的尺寸均为 30x30(3x3 内核网格使宽度和高度损失 2 个像素)。第二个卷积应用了更多内核,因此现在有 16 个尺寸为 28x28 的输出 channel (同样,3x3 内核网格使宽度和高度损失 2 个像素)。现在我期望下一层有 16x28x28 节点,因为 16 个输出 channel 中的每一个都有 28x28 像素。不知何故,这是不正确的,下一层包含 16x6x6 节点。为什么这是真的?

问题 2:第二个卷积层从 6 个输入 channel 变为 16 个输出 channel 。这是怎么做到的?

在第一个卷积层中,我们从一个输入 channel 变为六个输入 channel ,这对我来说很有意义。您只需将六个内核应用于单个输入 channel 即可获得六个输出 channel 。从六个输入 channel 到十六个输出 channel 对我来说没有多大意义。不同的内核是如何应用的?您是否将两个内核应用于前五个输入 channel 以达到十个输出 channel ,并将六个内核应用于最后一个输入 channel ,以便总数达到十六个输出 channel ?或者神经网络是否学习自己使用 x 内核并将它们应用到它认为最合适的输入 channel ?

最佳答案

我现在可以自己回答这些问题了。

问题 1:要了解为什么需要 32x32 图像才能使该神经网络工作,请考虑以下因素:

第 1 层:首先,使用 3x3 内核进行卷积。由于图像的尺寸为 32x32,因此将产生 30x30 的网格。接下来,将最大池化应用于网格,内核为 2x2,步长为 2,生成尺寸为 15x15 的网格。

第 2 层:首先,将 3x3 内核应用于 15x15 网格,得到 13x13 网格。接下来,应用最大池化,使用 2x2 内核和 2 步幅,形成尺寸为 6x6 的网格。我们得到一个 6x6 网格而不是 7x7 网格,因为默认情况下使用 Floor 函数而不是 ceil 函数。

由于第 2 层中的卷积有 16 个输出 channel ,因此第一个线性层需要 16x6x6 节点!我们看到所需的输入确实是一个 32x32 图像。

问题 2:每个输出 channel 都是通过将六个不同的内核应用于每个输入 channel 并对结果求和来创建的。 documentation 对此进行了解释。 .

关于python - 使用 Pytorch 进行深度学习 : understanding the neural network example,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57822568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com