-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
activations.py
359 lines (258 loc) · 9.06 KB
/
activations.py
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
from abc import ABC, abstractmethod
import numpy as np
class ActivationBase(ABC):
def __init__(self, **kwargs):
super().__init__()
def __call__(self, z):
if z.ndim == 1:
z = z.reshape(1, -1)
return self.fn(z)
@abstractmethod
def fn(self, z):
raise NotImplementedError
@abstractmethod
def grad(self, x, **kwargs):
raise NotImplementedError
class Sigmoid(ActivationBase):
"""
A logistic sigmoid activation function.
"""
def __init__(self):
super().__init__()
def __str__(self):
return "Sigmoid"
def fn(self, z):
return 1 / (1 + np.exp(-z))
def grad(self, x):
return self.fn(x) * (1 - self.fn(x))
def grad2(self, x):
return self.grad(x) * (1 - 2 * self.fn(x))
class ReLU(ActivationBase):
"""
A rectified linear activation function.
ReLU(x) =
x if x > 0
0 otherwise
ReLU units can be fragile during training and can "die". For example, a
large gradient flowing through a ReLU neuron could cause the weights to
update in such a way that the neuron will never activate on any datapoint
again. If this happens, then the gradient flowing through the unit will
forever be zero from that point on. That is, the ReLU units can
irreversibly die during training since they can get knocked off the data
manifold.
For example, you may find that as much as 40% of your network can be "dead"
(i.e. neurons that never activate across the entire training dataset) if
the learning rate is set too high. With a proper setting of the learning
rate this is less frequently an issue.
- Andrej Karpathy
"""
def __init__(self):
super().__init__()
def __str__(self):
return "ReLU"
def fn(self, z):
return np.clip(z, 0, np.inf)
def grad(self, x):
return (x > 0).astype(int)
def grad2(self, x):
return np.zeros_like(x)
class LeakyReLU(ActivationBase):
"""
'Leaky' version of a rectified linear unit (ReLU).
f(x) =
alpha * x if x < 0
x otherwise
Leaky ReLUs are designed to address the vanishing gradient problem in ReLUs
by allowing a small non-zero gradient when x is negative.
Parameters
----------
alpha: float (default: 0.3)
Activation slope when x < 0
References
----------
- [Rectifier Nonlinearities Improve Neural Network Acoustic Models](
https://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf)
"""
def __init__(self, alpha=0.3):
self.alpha = alpha
super().__init__()
def __str__(self):
return "Leaky ReLU(alpha={})".format(self.alpha)
def fn(self, z):
_z = z.copy()
_z[z < 0] = _z[z < 0] * self.alpha
return _z
def grad(self, x):
out = np.ones_like(x)
out[x < 0] *= self.alpha
return out
def grad2(self, x):
return np.zeros_like(x)
class Tanh(ActivationBase):
"""
A hyperbolic tangent activation function.
"""
def __init__(self):
super().__init__()
def __str__(self):
return "Tanh"
def fn(self, z):
return np.tanh(z)
def grad(self, x):
return 1 - np.tanh(x) ** 2
def grad2(self, x):
return -2 * np.tanh(x) * self.grad(x)
class Affine(ActivationBase):
"""
An affine activation function.
Parameters
----------
slope: float (default: 1)
Activation slope
intercept: float (default: 0)
Intercept/offset term
"""
def __init__(self, slope=1, intercept=0):
self.slope = slope
self.intercept = intercept
super().__init__()
def __str__(self):
return "Affine(slope={}, intercept={})".format(self.slope, self.intercept)
def fn(self, z):
return self.slope * z + self.intercept
def grad(self, x):
return self.slope * np.ones_like(x)
def grad2(self, x):
return np.zeros_like(x)
class Identity(Affine):
"""
Identity activation function
"""
def __init__(self):
super().__init__(slope=1, intercept=0)
def __str__(self):
return "Identity"
class ELU(ActivationBase):
"""
Exponential linear unit.
ELU(x) =
x if x >= 0
alpha * (e^x - 1) otherwise
ELUs are intended to address the fact that ReLUs are strictly nonnegative
and thus have an average activation > 0, increasing the chances of internal
covariate shift and slowing down learning. ELU units address this by (1)
allowing negative values when x < 0, which (2) are bounded by a value -1 *
`alpha`. Similar to leaky / parametric ReLUs, the negative activation
values help to push the average unit activation towards 0. Unlike leaky /
parametric ReLUs, however, the boundedness of the negative activation
allows for greater robustness in the face of large negative values,
allowing the function to avoid conveying the *degree* of "absence"
(negative activation) in the input.
Parameters
----------
alpha : float (default: 1)
Slope of negative segment
References
----------
- [Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs)](https://arxiv.org/abs/1511.07289)
"""
def __init__(self, alpha=1.0):
self.alpha = alpha
super().__init__()
def __str__(self):
return "ELU(alpha={})".format(self.alpha)
def fn(self, z):
# z if z > 0 else alpha * (e^z - 1) """
return np.where(z > 0, z, self.alpha * (np.exp(z) - 1))
def grad(self, x):
# 1 if x >= 0 else alpha * e^(z)
return np.where(x >= 0, np.ones_like(x), self.alpha * np.exp(x))
def grad2(self, x):
# 0 if x >= 0 else alpha * e^(z)
return np.where(x >= 0, np.zeros_like(x), self.alpha * np.exp(x))
class Exponential(ActivationBase):
"""
Exponential (base e) activation function.
"""
def __init__(self):
super().__init__()
def __str__(self):
return "Exponential"
def fn(self, z):
return np.exp(z)
def grad(self, x):
return np.exp(x)
def grad2(self, x):
return np.exp(x)
class SELU(ActivationBase):
"""
Scaled exponential linear unit (SELU).
SELU(x) = scale * ELU(x, alpha)
= scale * x if x >= 0
= scale * [alpha * (e^x - 1)] otherwise
SELU units, when used in conjunction with proper weight initialization and
regularization techniques, encourage neuron activations to converge to
zero-mean and unit variance without explicit use of e.g., batchnorm.
For SELU units, the `alpha` and `scale` values are constants chosen so that
the mean and variance of the inputs are preserved between consecutive
layers. As such the authors propose weights be initialized using
Lecun-Normal initialization: w ~ N(0, 1 / fan_in), and to use the dropout
variant `alpha-dropout` during regularization. See the reference for more
information (especially the appendix ;-) )
References
----------
- [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)
"""
def __init__(self):
self.alpha = 1.6732632423543772848170429916717
self.scale = 1.0507009873554804934193349852946
self.elu = ELU(alpha=self.alpha)
super().__init__()
def __str__(self):
return "SELU"
def fn(self, z):
return self.scale * self.elu.fn(z)
def grad(self, x):
return np.where(
x >= 0, np.ones_like(x) * self.scale, np.exp(x) * self.alpha * self.scale
)
def grad2(self, x):
return np.where(x >= 0, np.zeros_like(x), np.exp(x) * self.alpha * self.scale)
class HardSigmoid(ActivationBase):
"""
A "hard" sigmoid activation function.
HardSigmoid(x) =
0 if x < -2.5
0.2 * x + 0.5 if -2.5 <= x <= 2.5.
1 if x > 2.5
The hard sigmoid is a piecewise linear approximation of the logistic
sigmoid that is computationally more efficient to compute.
"""
def __init__(self):
super().__init__()
def __str__(self):
return "Hard Sigmoid"
def fn(self, z):
return np.clip((0.2 * z) + 0.5, 0.0, 1.0)
def grad(self, x):
return np.where((x >= -2.5) & (x <= 2.5), 0.2, 0)
def grad2(self, x):
return np.zeros_like(x)
class SoftPlus(ActivationBase):
"""
A softplus activation function.
SoftPlus(x) = log(1 + e^x)
In contrast to the ReLU function, softplus is differentiable everywhere
(including 0). It is, however, less computationally efficient to compute.
The derivative of the softplus activation is the logistic sigmoid.
"""
def __init__(self):
super().__init__()
def __str__(self):
return "SoftPlus"
def fn(self, z):
return np.log(np.exp(z) + 1)
def grad(self, x):
return np.exp(x) / (np.exp(x) + 1)
def grad2(self, x):
return np.exp(x) / ((np.exp(x) + 1) ** 2)