1
1
"""
2
2
This is a module to be used as a reference for building other modules
3
3
"""
4
- from sklearn .base import BaseEstimator
5
- from sklearn .utils import check_X_y , check_array
4
+ import numpy as np
5
+ from sklearn .base import BaseEstimator , ClassifierMixin
6
+ from sklearn .utils .validation import check_X_y , check_array , check_is_fitted
7
+ from sklearn .utils .multiclass import unique_labels
8
+ from sklearn .metrics import euclidean_distances
9
+
6
10
7
11
class TemplateEstimator (BaseEstimator ):
8
12
""" A template estimator to be used as a reference implementation .
9
-
13
+
10
14
Parameters
11
15
----------
12
16
demo_param : str, optional
@@ -21,7 +25,7 @@ def fit(self, X, y):
21
25
Parameters
22
26
----------
23
27
X : array-like or sparse matrix of shape = [n_samples, n_features]
24
- The training input samples.
28
+ The training input samples.
25
29
y : array-like, shape = [n_samples] or [n_samples, n_outputs]
26
30
The target values (class labels in classification, real numbers in
27
31
regression).
@@ -47,4 +51,63 @@ def predict(self, X):
47
51
Returns :math:`x^2` where :math:`x` is the first column of `X`.
48
52
"""
49
53
X = check_array (X )
50
- return X [:, 0 ]** 2
54
+ return X [:, 0 ]** 2
55
+
56
+
57
+ class TemplateClassifier (BaseEstimator , ClassifierMixin ):
58
+ """ An example for a classifier which implements a 1-NN algorithm.
59
+
60
+ Parameters
61
+ ----------
62
+ demo_param : str, optional
63
+ A parameter used for demonstation of how to pass and store paramters.
64
+ """
65
+ def __init__ (self , demo_param = 'demo' ):
66
+ self .demo_param = demo_param
67
+
68
+ def fit (self , X , y ):
69
+ """A reference implementation of a fitting function for a classifier.
70
+
71
+ Parameters
72
+ ----------
73
+ X : array-like or sparse matrix of shape = [n_samples, n_features]
74
+ The training input samples.
75
+ y : array-like, shape = [n_samples]
76
+ The target values. An array of int.
77
+ Returns
78
+ -------
79
+ self : object
80
+ Returns self.
81
+ """
82
+ # Check that X and y have correct shape
83
+ X , y = check_X_y (X , y )
84
+ # Store the classes seen durind fit
85
+ self .classes_ = unique_labels (y )
86
+
87
+ self .X_ = X
88
+ self .y_ = y
89
+ # Return the classifier
90
+ return self
91
+
92
+ def predict (self , X ):
93
+ """ A reference implementation of a prediction for a classifier.
94
+
95
+ Parameters
96
+ ----------
97
+ X : array-like of shape = [n_samples, n_features]
98
+ The input samples.
99
+
100
+ Returns
101
+ -------
102
+ y : array of int of shape = [n_samples]
103
+ The label for each sample is the label of the closest sample
104
+ seen udring fit.
105
+ """
106
+ # Check is fit had been called
107
+ check_is_fitted (self , ['X_' , 'y_' ])
108
+
109
+ # Input validation
110
+ X = check_array (X )
111
+
112
+ closest = np .argmin (euclidean_distances (X , self .X_ ), axis = 1 )
113
+ return self .y_ [closest ]
0 commit comments