forked from rushter/MLAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregularizers.py
More file actions
35 lines (23 loc) · 799 Bytes
/
regularizers.py
File metadata and controls
35 lines (23 loc) · 799 Bytes
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
# coding:utf-8
import numpy as np
from autograd import elementwise_grad
class Regularizer(object):
def __init__(self, C=0.01):
self.C = C
self._grad = elementwise_grad(self._penalty)
def _penalty(self, weights):
raise NotImplementedError()
def grad(self, weights):
return self._grad(weights)
def __call__(self, weights):
return self.grad(weights)
class L1(Regularizer):
def _penalty(self, weights):
return self.C * np.abs(weights)
class L2(Regularizer):
def _penalty(self, weights):
return self.C * weights ** 2
class ElasticNet(Regularizer):
"""Linear combination of L1 and L2 penalties."""
def _penalty(self, weights):
return 0.5 * self.C * weights ** 2 + (1.0 - self.C) * np.abs(weights)