-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_base.py
111 lines (83 loc) · 2.52 KB
/
_base.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
from abc import ABCMeta, abstractmethod
import numpy as np
from .metrics import accuracy_score, r2_score
class BaseClassifire(metaclass=ABCMeta):
"""Base class for all classifires"""
@abstractmethod
def fit(self, X, y):
pass
@abstractmethod
def predict(self, X):
pass
def score(self, X: np.ndarray, y: np.ndarray) -> float:
"""
Return accuracy score.
Args:
X (np.ndarray):
Test samples. 2d numpy array of shape
(n_samples, n_features).
y (np.ndarray):
True labels for `X`. 1d numpy array of shape
(n_samples,).
Returns:
float: Mean accuracy of `self.predict(X)` w.r.t. `y`.
"""
return accuracy_score(y, self.predict(X))
class BaseRegressor(metaclass=ABCMeta):
"""Base class for all regressors"""
@abstractmethod
def fit(self, X, y):
pass
@abstractmethod
def predict(self, X):
pass
def score(self, X: np.ndarray, y: np.ndarray) -> float:
"""
Return R^2 score.
Args:
X (np.ndarray):
Test samples. 2d numpy array of shape
(n_samples, n_features).
y (np.ndarray):
True values for `X`. 1d numpy array of shape
(n_samples,).
Returns:
float: R^2 score of `self.predict(X)` w.r.t. `y`.
"""
return r2_score(y, self.predict(X))
class BaseCluster(metaclass=ABCMeta):
"""Base class for all clusterers"""
@abstractmethod
def fit(self, X):
pass
@abstractmethod
def predict(self, X):
pass
def fit_predict(self, X: np.ndarray) -> np.ndarray:
"""
Fit training data and predict labels.
Args:
X (np.ndarray): 2d numpy array of training data.
Returns:
np.ndarray: 1d numpy array of predicted labels.
"""
self.fit(X)
return self.predict(X)
class BaseTransformer(metaclass=ABCMeta):
"""Base class for all transformers"""
@abstractmethod
def fit(self, X):
pass
@abstractmethod
def transform(self, X):
pass
def fit_transform(self, X: np.ndarray) -> np.ndarray:
"""
Fit training data and transform it.
Args:
X (np.ndarray): 2d numpy array of training data.
Returns:
np.ndarray: 2d numpy array of transformed data.
"""
self.fit(X)
return self.transform(X)