maxpooling 的 C++ 實現

這裏原理可以參考 pooling的原理與Python實現,這裏的 C++ 實現也是主要參考這裏的 python 實現來改的。(PS. 今年寒武紀秋招筆試題就有一題這個)

#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>

using namespace std;

vector<vector<int>> maxpooling(vector<vector<int>> map, int k_w, int k_h, int s_w, int s_h)
{
	int row = map.size(); int col = map[0].size();
	int out_row = 1+(row-k_h)/s_h, out_col = 1+(col-k_w)/s_w;
	int mod_row = row%s_h, mod_col = col%s_w;
	if (mod_row != 0) out_row++;
	if (mod_col != 0) out_col++;

	vector<vector<int>> res(out_row, vector<int>(out_col, 0));
	vector<vector<int>> pad_map(map);

	for (int i=0;i<row;i++)
		for (int j = 0; j < k_h - mod_row; j++)
		{
			pad_map[i].push_back(map[i][col - 1]);
		}
	for (int j = 0; j < k_w - mod_col; j++)
	{
		pad_map.push_back(pad_map[row - 1]);
	}

	for(int i=0;i<out_row;i++)
		for (int j = 0; j < out_col; j++)
		{
			int start_x = j*s_w;
			int start_y = i*s_h;
			vector<int> temp;
			for(int ii=0;ii<k_w;ii++)
				for (int jj = 0; jj < k_h; jj++)
				{
					temp.push_back(pad_map[start_y + jj][start_x + ii]);
				}
			sort(temp.begin(), temp.end());
			res[i][j] = temp[temp.size() - 1];
		}
	return res;
}

int main()
{
	/*int n, m, k_w, k_h, s_w, s_h;
	cin >> n >> m;
	vector<vector<int>> f_map(n,vector<int>(m,0));
	cin >> k_h >> k_w;
	cin >> s_h >> s_w;
	for(int i=0;i<n;i++)
		for (int j = 0; j < m; j++)
		{
			cin >> f_map[i][j];
		}
		*/
	vector<vector<int>> f_map = {{1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11, 12}};
	//auto res = maxpooling(f_map, k_w, k_h, s_w, s_h);
	auto res = maxpooling(f_map, 2, 2, 2, 2);
	for (auto l : res)
	{
		for (auto ll : l)
		{
			cout << ll << " ";
		}
		cout << endl;
	}

	system("pause");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章