首页 > 解决方案 > 权重卷积层有多少?

问题描述

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

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)

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

我错过了什么吗?

标签: pythonpytorchconv-neural-network

解决方案


这很重要,因为您正在对图像进行 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 conv 在此处输入图像描述


推荐阅读