C++ 实现 maxpooling 计算

C++ implement Maxpooling

输入参数:featmap, kernel_size (h, w), stride

输出参数:featmap

注意实现
  1. 计算输出 feat 大小,难点: 如果 featmap 的大小(高/宽)无法整除 stride 时,则需要进行 padding;
  2. 注意 pading 时的填充计算;
  3. 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;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值