-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactivations.c
116 lines (97 loc) · 2.04 KB
/
activations.c
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include "activations.h"
#include <math.h>
inline float linear(float z) {
return z;
}
float sigmoid(float z) {
return 1 / (1 + expf(-z));
}
float logistic(float z) {
return sigmoid(z);
}
float a_tanh(float z) {
return tanhf(z);
}
float a_atan(float z) {
return atanf(z);
}
float relu(float z) {
if (z < 0) return 0;
return z;
}
float leaky_relu(float z) {
if (z < 0) return z * 0.01;
return z;
}
inline float deriv_linear(float a) {
return 1;
}
activation_deriv_t getActivationDerivative(activation_func_t a) {
if (a == sigmoid) {
return deriv_sigmoid;
}
if (a == logistic) {
return deriv_logistic;
}
if (a == a_tanh) {
return deriv_a_tanh;
}
if (a == a_atan) {
return deriv_a_atan;
}
if (a == relu) {
return deriv_relu;
}
if (a == leaky_relu) {
return deriv_leaky_relu;
}
return deriv_linear;
}
float deriv_sigmoid(float a) {
float sig_a = sigmoid(a);
float res = sig_a * (1 - sig_a);
return res;
}
float deriv_logistic(float a) {
return deriv_sigmoid(a);
}
float deriv_a_tanh(float a) {
float tanh_a = a_tanh(a);
float res = 1.0 - (tanh_a*tanh_a);
return res;
}
float deriv_a_atan(float a) {
float res = 1 / ((a * a) + 1);
return res;
}
float deriv_relu(float a) {
if (a < 0) return 0;
return 1;
}
float deriv_leaky_relu(float a) {
if (a < 0) return 0.01;
return 1;
}
float amaxf(float* z, int size) {
int m = z[0];
for (int i=0;i<size;i++) {
if (z[i] > m) m = z[i];
}
return m;
}
// Can be more accurate with softmax by computing the Jacobian for backprop
// but would require so much more effort that its not worth it
// Modifies input in place; does not fit typedef
void softmax(float* z, int size) {
float maxv = amaxf(z, size);
float denom = 0;
for (int i=0;i<size;i++) {
denom = denom + expf(z[i]);
}
if (denom == 0) {
denom = 0.0001;
}
for (int i=0;i<size;i++) {
z[i] = expf(z[i]) / denom;
}
}