目录
卷积神经网络的基础算子
卷积神经网络是目前计算机视觉中使用最普遍的模型结构,如下图所示,由M个卷积层和b个汇聚层组合作用在输入图片上,在网络的最后通常会加入K个全连接层。
从上图可以看出,卷积网络是由多个基础的算子组合而成。下面我们先实现卷积网络的两个基础算子:卷积层算子和汇聚层算子。
首先我们实现卷积网络的两个基础算子:卷积层算子和汇聚层算子
卷积层算子
卷积层是指用卷积操作来实现神经网络中一层。
为了提取不同种类的特征,通常会使用多个卷积核一起进行特征提取。
多通道卷积
多通道卷积层算子
1. 多通道卷积卷积层的代码实现
2. Pytorch:torch.nn.Conv2d()代码实现
3. 比较自定义算子和框架中的算子
代码实现:
import torch
import torch.nn as nn
class Conv2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0,weight_attr=[],bias_attr=[]):
super(Conv2D, self).__init__()
# 创建卷积核
weight_attr = torch.randn([out_channels, in_channels, kernel_size, kernel_size])
weight_attr = torch.nn.init.constant(torch.tensor(weight_attr, dtype=torch.float32), val=1.0)
self.weight = torch.nn.Parameter(weight_attr)
# 创建偏置
bias_attr = torch.zeros([out_channels, 1])
bias_attr = torch.tensor(bias_attr, dtype=torch.float32)
self.bias = torch.nn.Parameter(bias_attr)
self.stride = stride
self.padding = padding
# 输入通道数
self.in_channels = in_channels
# 输出通道数
self.out_channels = out_channels
# 基础卷积运算
def single_forward(self, X, weight):
# 零填充
new_X = torch.zeros([X.shape[0], X.shape[1]+2*self.padding, X.shape[2]+2*self.padding])
new_X[:, self.padding:X.shape[1]+self.padding, self.padding:X.shape[2]+self.padding] = X
u, v = weight.shape
output_w = (new_X.shape[1] - u) // self.stride + 1
output_h = (new_X.shape[2] - v) // self.stride + 1
output = torch.zeros([X.shape[0], output_w, output_h])
for i in range(0, output.shape[1]):
for j in range(0, output.shape[2]):
output[:, i, j] = torch.sum(new_X[:, self.stride*i:self.stride*i+u, self.stride*j:self.stride*j+v]*weight, [1, 2])
return output
def forward(self, inputs):
"""
输入:
- inputs:输入矩阵,shape=[B, D, M, N]
- weights:P组二维卷积核,shape=[P, D, U, V]
- bias:P个偏置,shape=[P, 1]
"""
feature_maps = []
# 进行多次多输入通道卷积运算
p=0
for w, b in zip(self.weight, self.bias): # P个(w,b),每次计算一个特征图Zp
multi_outs = []
# 循环计算每个输入特征图对应的卷积结果
for i in range(self.in_channels):
single = self.single_forward(inputs[:, i, :, :], w[i])
multi_outs.append(single)
# print("Conv2D in_channels:",self.in_channels,"i:",i,"single:",single.shape)
# 将所有卷积结果相加
feature_map = torch.sum(torch.stack(multi_outs), 0) + b # Zp