diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..aa1a10df 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,12 +37,11 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ - i = 0 - j = 0 + if not isinstance(X, np.ndarray) or X.ndim != 2: + raise ValueError("X must be a 2D numpy array.") - # TODO - - return i, j + flat_idx = np.argmax(X) + return np.unravel_index(flat_idx, X.shape) def wallis_product(n_terms): @@ -62,6 +61,12 @@ 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 not isinstance(n_terms, int) or n_terms < 0: + raise ValueError("n_terms must be a non-negative integer.") + + if n_terms == 0: + return 1.0 + + k = np.arange(1, n_terms + 1, dtype=np.float64) + terms = (2 * k / (2 * k - 1)) * (2 * k / (2 * k + 1)) + return 2.0 * np.prod(terms) diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..b2fcc6c0 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -22,53 +22,88 @@ import numpy as np from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin -from sklearn.utils.validation import check_X_y -from sklearn.utils.validation import check_array from sklearn.utils.validation import check_is_fitted from sklearn.utils.multiclass import check_classification_targets +from sklearn.utils.validation import check_is_fitted +from sklearn.utils.validation import check_X_y +from sklearn.utils.validation import check_array -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. + """Fit the classifier by memorizing the training set. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training input samples. + + y : ndarray of shape (n_samples,) + Target class labels. - And describe parameters + Returns + ------- + self : OneNearestNeighbor + Fitted estimator. """ X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - - # XXX fix + self.X_ = X + self.y_ = y return self def predict(self, X): - """Write docstring. + """Predict class labels for samples in `X`. + + Parameters + ---------- + X : ndarray of shape (n_queries, n_features) + Input samples. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_queries,) + Predicted class labels. """ - check_is_fitted(self) + check_is_fitted( + self, attributes=["X_", "y_", "classes_", "n_features_in_"] + ) X = check_array(X) - y_pred = np.full( - shape=len(X), fill_value=self.classes_[0], - dtype=self.classes_.dtype - ) + if X.shape[1] != self.n_features_in_: + raise ValueError( + f"X has {X.shape[1]} features, but {self.__class__.__name__} " + f"is expecting {self.n_features_in_} features as input" + ) - # XXX fix - return y_pred + diff = X[:, np.newaxis, :] - self.X_[np.newaxis, :, :] + dists = np.sum(diff ** 2, axis=2) + nn_idx = np.argmin(dists, axis=1) + return self.y_[nn_idx] def score(self, X, y): - """Write docstring. + """ + Compute accuracy of the classifier on the given test data and labels. - And describe parameters + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Test samples. + + y : ndarray of shape (n_samples,) + True labels for `X`. + + Returns + ------- + accuracy : float + Mean accuracy of predictions on `X` compared to `y`. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - - # XXX fix - return y_pred.sum() + return float(np.mean(y_pred == y)) diff --git a/students.txt b/students.txt index 6813300e..d358425e 100644 --- a/students.txt +++ b/students.txt @@ -15,7 +15,7 @@ Burtin Léo Chaabouni Kenza Chauhan Bhavesh Chou Wei-Chieh X -Clot Augustin +Clot Augustin X De Sauvan D'Aramon Ithier X Descazeaud Lucien X Despréaux Maxime X @@ -60,7 +60,7 @@ Liard Eléanor X Liu Guangyue X Liu Yunxian X Lucille Maximilien X -Mahé Blanche +Mahé Blanche X Martin Justin X Massias Mathurin Massoud Alexandre.....X