CNN卷积层——nn.Conv1d和nn.Conv2d

  • 写在前面:【图片护体】
    在这里插入图片描述

1 一维卷积神经网络(nn.Conv1d)

一维卷积常常用在序列模型、自然语言处理领域
一维卷积用于文本数据,只对宽度进行卷积,对高度不卷积。

1.1 函数原型

class torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

1.2 参数说明

in_channels:在文本应用中,即为词向量的维度
out_channels:卷积产生的通道数,有多少个out_channels,就需要多少个一维卷积(也就是卷积核的数量)
kernel_size:卷积核的尺寸;卷积核的第二个维度由in_channels决定,所以实际上卷积核的大小为kernel_size * in_channels
padding:对输入的每一条边,补充0的层数

1.3 代码示例

输入:batch_size=32, 句子的最大长度是35,词向量维度是256
目标:句子分类(2类)

conv1 = nn.Conv1d(in_channels=256, out_channels=100, kernel_size=2)
input = torch.randn(32, 35, 256)
input = input.permute(0, 2, 1)
output = conv1(input)
print(output.shape)
  • 输出:
torch.Size([32, 100, 34])

2 二维卷积神经网络(nn.Conv2d)

一般来说,二维卷积nn.Conv2d用于图像处理,对宽度和高度都进行卷积。

2.1 函数原型

  • 二维卷积的模型太多了,这个是网上找的贴了。

这里是参考到lizz2276的博客,“CNN一维卷积详解”

class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
class CNN(nn.Module):
    def __init__(self):
        nn.Model.__init__(self)
 
        self.conv1 = nn.Conv2d(1, 6, 5)  # 输入通道数为1,输出通道数为6
        self.conv2 = nn.Conv2d(6, 16, 5)  # 输入通道数为6,输出通道数为16
        self.fc1 = nn.Linear(5 * 5 * 16, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)
 
    def forward(self, x):
        # 输入x -> conv1 -> relu -> 2x2窗口的最大池化
        x = self.conv1(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        # 输入x -> conv2 -> relu -> 2x2窗口的最大池化
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        # view函数将张量x变形成一维向量形式,总特征数不变,为全连接层做准备
        x = x.view(x.size()[0], -1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

猜你喜欢

转载自blog.csdn.net/weixin_42521185/article/details/124435507#comments_21119327