C++ implement Maxpooling
输入参数:featmap, kernel_size (h, w), stride
输出参数:featmap
注意实现
- 计算输出 feat 大小,难点: 如果 featmap 的大小(高/宽)无法整除 stride 时,则需要进行 padding;
- 注意 pading 时的填充计算;
- h,w 不一定相等,stride h,w 也不一定相等;
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void print(vector<vector<int> > res){
for (auto l: res)
{
for (auto ll: l)
{
cout << ll << " ";
}
cout << endl;
}
cout << endl;
}
vector<vector<int> > maxpooling(vector<vector<int> > featmap, int k_h, int k_w, int s_h, int s_w){
int feat_h = featmap.size(), feat_w = featmap[0].size();
int out_h = (feat_h - k_h) / s_h + 1;
int out_w = (feat_w - k_w) / s_w + 1;
int mod_h = (feat_h - k_h) % s_h;
int mod_w = (feat_w - k_w) % s_w;
if(mod_h){
out_h ++;
}
if(mod_w){
out_w ++;
}
vector<vector<int> > out_feat(out_h, vector<int>(out_w));
vector<vector<int> > pad_feat(featmap);
if(mod_w){
for(int i = 0; i < feat_h; i++){
for(int j = 0; j < s_w - mod_w; j++){
pad_feat[i].push_back(pad_feat[i][feat_w - 1]);
}
}
}
if(mod_h){
for(int i = 0; i < s_h - mod_h; i++){
pad_feat.push_back(pad_feat[feat_h - 1]);
}
}
// print(pad_feat);
for(int i = 0; i < out_h; i++){
for(int j = 0; j < out_w; j++){
int start_h = i * s_h;
int start_w = j * s_w;
int maxV = pad_feat[start_h][start_w];
// cout << start_h << " " << start_w << endl;
for(int k_i = 0; k_i < k_h; k_i++){
for(int k_j = 0; k_j < k_w; k_j++){
maxV = max(maxV, pad_feat[start_h + k_i][start_w + k_j]);
}
}
out_feat[i][j] = maxV;
}
}
return out_feat;
}
int main(){
vector<vector<int> > f_map = {
{1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11, 12},{9, 10, 11, 12}};
print(f_map);
auto res = maxpooling(f_map, 3, 3, 3, 3);
// auto res = maxpooling(f_map, 2, 2, 2, 2);
print(res);
return 0;
}