Pytorch 神经网络模块之 Convolution Layers

1. torch.nn.Conv2d

   nn.Conv2d 是二维卷积方法,主要做图像卷积,它的函数原型如下:

"""
in_channels - 输入图像的通道数,也是输入层神经元的个数
out_channels - 输出图像的通道数,也是输出层神经元的个数
kernel_size - 单个卷积核尺寸。可以设为 1 个 int 型数或者一个 (int, int) 型的tuple
stride - 卷积核移动步长。可以设为 1 个 int 型数或者一个 (int, int) 型的tuple
padding - 如果提供的是单个整数,那表示在四周填充 0 的圈数,如果提供的是元组,第一个参数表示在填充高度(上下两侧一起填充),第二个参数表示填充宽度
dilation -
groups -
bias - 为每个神经元的输出的每个通道图像设置偏置量
"""
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

   在 torch 中输入的数据都是小批量的,所以在输入的时候需要指定 batch 大小。举个例子:

import torch

in_channels, out_channels= 5, 10
height, width = 100, 200 # 图像大小
kernel_size = 3
batch_size = 6

input = torch.randn(batch_size, in_channels, height, width)
conv_layer = torch.nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size)
output = conv_layer(input)

print(input.shape)              # torch.Size([6, 5, 100, 200])
print(conv_layer.weight.shape)  # torch.Size([10, 5, 3, 3])
print(output.shape)             # torch.Size([6, 10, 98, 198])

 

posted @ 2020-12-07 15:31  _yanghh  阅读(287)  评论(0编辑  收藏  举报