-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSoftMaxLayer.cpp
More file actions
68 lines (64 loc) · 1.82 KB
/
Copy pathSoftMaxLayer.cpp
File metadata and controls
68 lines (64 loc) · 1.82 KB
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
#include "DeepLearning.h"
SoftMaxLayer::SoftMaxLayer(int h, int w){
height = h;
width = w;
sum.resize(width);
for(int i = 0;i < batchSize;i++){
Array tmp(height,width);
output.push_back(tmp);
error.push_back(tmp);
}
}
void SoftMaxLayer::AddTogether(int n){
for(int j = 0;j < width;j++){
sum[j] = 0;
}
for(int i = 0;i < height;i++){
for(int j = 0;j < width;j++){
sum[j] += output[n].arr[i][j];
}
}
for(int j = 0;j < width;j++){
if(abs(sum[j]) < 1e-5){
int sign = (sum[j] > 0) ? 1 : -1;
sum[j] = 1e-5 * sign;
}
}
}
void SoftMaxLayer::forward(const vector<Array>& inp){
for(int n = 0;n < batchSize;n++){
if(inp[n].width != width || inp[n].height != height){
printf("Error : Unable to compute SoftMax Forward\n");
exit(0);
}
double mini = 1e10;
for(int i = 0;i < height;i++){
for(int j = 0;j < width;j++){
if(inp[n].arr[i][j] < mini){
mini = inp[n].arr[i][j];
}
}
}
for(int i = 0;i < height;i++){
for(int j = 0;j < width;j++){
output[n].arr[i][j] = exp(inp[n].arr[i][j] - mini);
}
}
AddTogether(n);
for(int i = 0;i < height;i++){
for(int j = 0;j < width;j++){
output[n].arr[i][j] = output[n].arr[i][j]/sum[j];
}
}
if(!output[n].CheckFinite()){
fprintf(fpDebug, "In SoftMaxLayer: Array called output\n");
fflush(fpDebug);
exit(0);
}
}
return;
}
void SoftMaxLayer::backward(const vector<Array>& err){
error = err;
return;
}