-
Notifications
You must be signed in to change notification settings - Fork 21
/
regularizer.py
74 lines (63 loc) · 1.66 KB
/
regularizer.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
import numpy as np
class Regularizer:
def __init__(self, param):
self._param = param
def regularize(self, W):
return 0
class L1Regularizer(Regularizer):
def __init__(self, param):
'''
Parameters
----------
param : Regularization strength
'''
super().__init__(param)
def regularize(self, W):
'''
Parameters
----------
W : Weights of model
Returns
-------
W : Weights regularized
'''
return self._param * np.where(W >= 0, 1, -1)
class L2Regularizer(Regularizer):
def __init__(self, param):
'''
Parameters
----------
param : Regularization strength
'''
super().__init__(param)
def regularize(self, W):
'''
Parameters
----------
W : Weights of model
Returns
-------
W : Weights regularized
'''
return self._param * W
class ElasticRegularizer(Regularizer):
def __init__(self, param, ratio):
'''
Parameters
----------
param : Regularization strength
ratio : The ElasticNet mixing parameter
'''
self.__l1 = L1Regularizer(param)
self.__l2 = L2Regularizer(param)
self.__ratio = ratio
def regularize(self, W):
'''
Parameters
----------
W : Weights of model
Returns
-------
W : Weights regularized
'''
return self.__ratio * self.__l1.regularize(W) + (1 - self.__ratio) * self.__l2.regularize(W)