diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..387c8303 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -40,8 +40,10 @@ def max_index(X): i = 0 j = 0 - # TODO + if not isinstance(X, np.ndarray) or X.ndim != 2: + raise ValueError("X must be a two-dimensional numpy array.") + i, j = np.unravel_index(np.argmax(X), X.shape) return i, j @@ -62,6 +64,9 @@ def wallis_product(n_terms): pi : float The approximation of order `n_terms` of pi using the Wallis product. """ - # XXX : The n_terms is an int that corresponds to the number of - # terms in the product. For example 10000. - return 0. + if n_terms == 0: + return 1.0 + + k = np.arange(1, n_terms + 1, dtype=float) + factors = (4 * k**2) / (4 * k**2 - 1) + return 2 * np.prod(factors) diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..85e140fa 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -28,29 +28,48 @@ from sklearn.utils.multiclass import check_classification_targets -class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. - - And describe parameters + """Store the training samples and their class labels. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training samples. + y : ndarray of shape (n_samples,) + Class labels for the training samples. + + Returns + ------- + self : OneNearestNeighbor + The fitted classifier. """ X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] + self.X_ = X.copy() + self.y_ = y.copy() - # XXX fix return self def predict(self, X): - """Write docstring. + """Predict the class of each sample using its nearest neighbor. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Samples to classify. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Predicted class labels. """ check_is_fitted(self) X = check_array(X) @@ -59,16 +78,35 @@ def predict(self, X): dtype=self.classes_.dtype ) - # XXX fix + if X.shape[1] != self.n_features_in_: + raise ValueError( + f"X has {X.shape[1]} features, but OneNearestNeighbor " + f"is expecting {self.n_features_in_} features as input" + ) + + for i, sample in enumerate(X): + distances = np.sum((self.X_ - sample) ** 2, axis=1) + nearest_index = np.argmin(distances) + y_pred[i] = self.y_[nearest_index] + return y_pred def score(self, X, y): - """Write docstring. - - And describe parameters + """Return the classification accuracy on the given samples. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Samples to classify. + y : ndarray of shape (n_samples,) + True class labels. + + Returns + ------- + score : float + Fraction of samples classified correctly. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)