diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..ff36a3a0 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -40,7 +40,14 @@ def max_index(X): i = 0 j = 0 - # TODO + if not isinstance(X, np.ndarray): + raise ValueError("Input should be a numpy array.") + + if X.ndim != 2: + raise ValueError("Input array should be 2D.") + + flat_idx = np.argmax(X) + i, j = flat_idx // X.shape[1], flat_idx % X.shape[1] return i, j @@ -62,6 +69,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. + pi = 2. + + if n_terms == 0: + return 1. + + for n in range(1, n_terms + 1): + pi *= (4 * n ** 2) / (4 * n ** 2 - 1) + + return pi diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..bef72c12 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,46 +29,93 @@ class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. + """Fit OneNearestNeighbor model according to the given training data. - And describe parameters + Check X and y for consistent length, enforce X to be 2D and y 1D, + and ensure that target y is of a non-regression type. + (The above is consistent with sklearn's documentation.) + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training data. + + y : ndarray of shape (n_samples,) + Target values. + + Returns + ------- + self : object + Model fit on the training data. """ 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. - - And describe parameters + """Perform classification on test data X. + + Check that the model is fitted and X is 2D. + By default, the input is checked to be a non-empty 2D array + containing only finite values. + (The above was taken from sklearn's documentation.) + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Test samples. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Predicted class labels for samples in X. """ - check_is_fitted(self) X = check_array(X) + check_is_fitted(self) + y_pred = np.full( shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) - # XXX fix + distances = np.linalg.norm(X[:, np.newaxis] - self.X_, axis=2) + nearest_neighbor_idx = np.argmin(distances, axis=1) + y_pred = self.y_[nearest_neighbor_idx] + return y_pred def score(self, X, y): - """Write docstring. + """Return the accuracy on the given test data and labels. + + Check that the model is fitted and that X and y have consistent length. + (The above was taken from sklearn's documentation.) + + 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 of self.predict(X) with respect to y. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)