diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..368d85b3 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -39,9 +39,12 @@ def max_index(X): """ i = 0 j = 0 - - # TODO - + if not isinstance(X, np.ndarray): + raise ValueError("Input must be a numpy array") + if X.ndim != 2: + raise ValueError("Input must be a 2D array") + idx_flat = np.argmax(X) + i, j = np.unravel_index(idx_flat, X.shape) return i, j @@ -62,6 +65,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. + product = 1.0 + for k in range(1, n_terms + 1): + product *= (4 * k ** 2) / (4 * k ** 2 - 1) + if n_terms == 0: + return 1.0 + return product * 2 diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..178a8a3f 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,7 +29,7 @@ class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass @@ -42,9 +42,10 @@ def fit(self, X, y): X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) + self.X_train_ = X + self.y_train_ = y self.n_features_in_ = X.shape[1] - # XXX fix return self def predict(self, X): @@ -58,8 +59,10 @@ def predict(self, X): shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) - - # XXX fix + for i, x in enumerate(X): + dist = np.linalg.norm(self.X_train_ - x, axis=1) + idx_min = np.argmin(dist) + y_pred[i] = self.y_train_[idx_min] return y_pred def score(self, X, y): @@ -70,5 +73,4 @@ def score(self, X, 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)