[C++ 基于Eigen库实现CRN前向推理]
第二部分:Conv2d实现
- 前言:(Eigen库使用记录)
- 第一部分:WavFile.class (实现读取wav/pcm,实现STFT)
- 第二部分:Conv2d实现
- 第三部分:TransposedConv2d实现 (mimo,padding,stride,dilation,kernel,outpadding)
- 第四部分:NonLinearity (Sigmoid,Tanh,ReLU,ELU,Softplus)
- 第五部分:LSTM
- GITHUB仓库
1. Conv2d介绍
1.1 参数介绍
这是pytorch官方源码
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: _size_2_t,
stride: _size_2_t = 1,
padding: _size_2_t = 0,
dilation: _size_2_t = 1,
groups: int = 1,
bias: bool = True,
padding_mode: str = 'zeros' # TODO: refine this type
):
-
in_channels:网络输入的通道数,简单理解为每个输入样本包含多个个FeatureMap。
-
out_channels:网络输出的通道数。即卷积核的个数
-
kernel_size:卷积核的大小,如果该参数是一个整数q,那么卷积核的大小是qXq。
至此,一个简单的卷积如图
-
stride:步长。是卷积过程中移动的步长。默认情况下是1。一般卷积核在输入图像上的移动是自左至右,自上至下。如果参数是一个整数那么就默认在水平和垂直方向都是该整数。如果参数是stride=(2, 1),2代表着高(h)进行步长为2,1代表着宽(w)进行步长为1。
加入步长后,当步长为2时,卷积如图:
-
padding:填充,默认是0值填充。改参数指定的是在边缘填充多少行或列的0值
如padding为1时,卷积如图
-
dilation:扩张。一般情况下,卷积核与输入图像对应的位置之间的计算是相同尺寸的,也就是说卷积核的大小是3X3,那么它在输入图像上每次作用的区域是3X3,这种情况下dilation=0。当dilation=1时,表示的是下图这种情况。
1.2 python实现
2. 基于Eigen的C++实现
2.1 Layer_Conv2d.h
//
// Created by Koer on 2022/10/31.
//
#ifndef CRN_LAYER_CONV2D_H
#define CRN_LAYER_CONV2D_H
#include "vector"
#include "mat.h"
#include "Eigen"
#include "tuple"
#include "Eigen/CXX11/Tensor"
class Layer_Conv2d {
public:
Layer_Conv2d();
Layer_Conv2d(int64_t in_ch, int64_t out_ch, std::pair<int64_t, int64_t> kernel = std::make_pair(1, 1),
std::pair<int64_t, int64_t> stride = std::make_pair(1, 1),
std::pair<int64_t, int64_t> dilation = std::make_pair(1, 1),
std::pair<int64_t, int64_t> padding = std::make_pair(0, 0));
void LoadState(MATFile *pmFile, const std::string &state_preffix);
void LoadTestState();
Eigen::Tensor<float_t, 4> forward(Eigen::Tensor<float_t, 4> &input)