小言_互联网的博客

maxpooling 的 C++ 实现

925人阅读  评论(0)

这里原理可以参考 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;
}

转载:https://blog.csdn.net/Chris_zhangrx/article/details/102370707
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场