pytorch之卷积神经网络nn.conv2d
卷积网络最基本的是卷积层,使用使用Pytorch中的nn.Conv2d类来实现二维卷积层,主要关注以下几个构造函数参数:
nn.Conv2d(self, in_channels, out_channels, kernel_size, stride, padding,bias=True))
参数:
in_channel: 输入数据的通道数;
out_channel: 输出数据的通道数,这个根据模型调整;
kennel_size: 卷积核大小;kennel_size=3,表示卷积大小(3,3), kennel_size=(3,5),表示卷积大小为非正方形核(3,5);
stride:步长,默认为1,与kennel_size类似,stride=3,表示上下左右移动步长均为3,stride=(3,5),表示左右移动步长是3,上下移动步长是4;
padding:默认是0填充
bias:默认是True,True表示含有偏置项
下面举一个简单例子:
import torch as t
import torch.nn as nn
print(t.__version__)
X = t.rand(4, 2, 3, 5)
print(X.shape)
conv2d = nn.Conv2d(in_channels=2, out_channels=3, kernel_size=3, stride=1, padding=2)
Y = conv2d(X)
print('Y.shape: ', Y.shape)
print('weight.shape: ', conv2d.weight.shape)
print('bias.shape: ', conv2d.bias.shape)
结果:
1.2.0
torch.Size([4, 2, 3, 5])
Y.shape: torch.Size([4, 3, 5, 7])
weight.shape: torch.Size([3, 2, 3, 3])
bias.shape: torch.Size([3])