diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..66fc4981 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,12 +37,17 @@ 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): + raise ValueError("X must be a numpy array") + if X.ndim != 2: + raise ValueError("X must be a two-dimensional numpy array") - # TODO + flat_index = np.argmax(X) - return i, j + # Convert flat index to 2D coordinates + i, j = np.unravel_index(flat_index, X.shape) + + return int(i), int(j) def wallis_product(n_terms): @@ -62,6 +67,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 + + n = np.arange(1, n_terms + 1) + terms = (4 * n ** 2) / ((4 * n ** 2) - 1) + product = np.prod(terms) + return 2 * product diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..562e6cc6 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -23,52 +23,91 @@ 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 -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 OneNearestNeighbor classifier. - And describe parameters + Store the training data for use in prediction. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training data features. + y : ndarray of shape (n_samples,) + Training data labels. + + Returns + ------- + self : object + Returns self. """ - X, y = check_X_y(X, y) + X, y = self._validate_data(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. + + For each sample, finds the nearest neighbor in the training data + and returns its label. - And describe parameters + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Test samples to predict. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Predicted class labels for each test sample. """ check_is_fitted(self) - X = check_array(X) + X = self._validate_data(X, reset=False) + y_pred = np.full( shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) - # XXX fix + for i, test_point in enumerate(X): + distances = np.linalg.norm(self.X_ - test_point, axis=1) + nearest_idx = np.argmin(distances) + y_pred[i] = self.y_[nearest_idx] + return y_pred def score(self, X, y): - """Write docstring. + """Calculate accuracy score. + + Computes the proportion of correctly classified samples. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Test samples. + y : ndarray of shape (n_samples,) + True labels for X. - And describe parameters + Returns + ------- + score : float + Accuracy score (proportion of correct predictions). """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)