-
Notifications
You must be signed in to change notification settings - Fork 2
/
max_pooling_layer.h
73 lines (59 loc) · 1.92 KB
/
max_pooling_layer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#pragma once
#include "layer.h"
#include "util.h"
namespace con {
class MaxPoolingLayer : public Layer {
public:
MaxPoolingLayer(const string &name, const int &kernel, const int &stride, Layer *prev) :
Layer(
name,
prev->num,
ceilDiv(prev->width - kernel, stride) + 1,
ceilDiv(prev->height - kernel, stride) + 1,
prev->depth,
prev),
kernel(kernel), stride(stride) {
reshape(num, width, height, depth, &maxIndex);
}
const int kernel;
const int stride;
void forward() {
for (int n = 0; n < num; n++) {
for (int d = 0; d < depth; d++) {
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
int index = getIndex(d, h, w);
output[n][index] = getMax(n, d, h, w, index);
}
}
}
}
}
void backProp(const vector<Vec> &nextErrors) {
clear(&errors);
for (int n = 0; n < num; n++) {
for (int i = 0; i < depth * height * width; i++) {
errors[n][maxIndex[n][i]] += nextErrors[n][i];
}
}
}
void applyUpdate(const Real &lr, const Real &momentum, const Real &decay) {}
private:
vector<Vec> maxIndex;
Real getMax(const int &n, const int &d, const int &h, const int &w, const int &outIndex) {
int startH = h * stride;
int startW = w * stride;
int pos = -1;
for (int i = startH; i < startH + kernel && i < inHeight; i++) {
for (int j = startW; j < startW + kernel && j < inWidth; j++) {
int index = d * inHeight * inWidth + i * inWidth + j;
if (pos == -1 || prev->output[n][index] > prev->output[n][pos]) {
pos = index;
}
}
}
maxIndex[n][outIndex] = pos;
return prev->output[n][pos];
}
};
}