卷积层有多少个权值?

Afs*_*ooy 1 python conv-neural-network pytorch

我有一个简单的卷积网络:

import torch.nn as nn 

class model(nn.Module):
def __init__(self, ks=1):
    super(model, self).__init__()
    self.conv1 = nn.Conv2d(in_channels=4, out_channels=32, kernel_size=ks, stride=1)

    self.fc1 = nn.Linear(8*8*32*ks, 64)
    self.fc2 = nn.Linear(64, 64)

def forward(self, x):
    x = F.relu(self.conv1(x))
    x = x.view(x.size(0), -1)
    x = F.relu(self.fc1(x))
    x = self.fc2(x)
    return x

cnn = model(1)
Run Code Online (Sandbox Code Playgroud)

由于内核大小为1且输出通道为32,我假设32*1*1该层中应该有权重。但是,当我询问pytorch权重矩阵的形状时cnn.conv1.weight.shape,它返回torch.Size([32, 4, 1, 1])。为什么输入通道的数量会对conv2d层的权重产生影响?

我错过了什么吗?

Mos*_*bib 6

这很重要,因为您正在对图像进行 2D 卷积,这意味着过滤器(内核)的深度必须等于 in_channels 的数量(pytorch 为您设置),因此真正的内核大小是[in_channels,1,1]。另一方面,我们可以说 out_channels 数量是内核的数量,因此weights = number of kernels * size of kernel = out_channels * (in_channels * kernel_size). 这是带有 3D 输入的 2D 转换 在此输入图像描述

  • 您在选择 Conv2d 时设置它。您告诉 pytorch 将内核“深度”设置为“in_channel”以便完成计算。如果您选择 Conv3d,则 `conv1.weight.shape` 的结果将为 `torch.Size([32, 1, 1, 1])`,如果您选择 Conv1d,则 `conv1.weight.shape` 的结果将为可以是 `torch.Size([32, 4, wedth, 1])` 或 `torch.Size([32, 1, 1, height])` 检查我添加到答案中的图像 (2认同)