diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..58427bc2 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -41,7 +41,13 @@ def max_index(X): 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 2D") + flat_index = np.argmax(X) + i, j = np.unravel_index(flat_index, X.shape) return i, j @@ -64,4 +70,10 @@ def wallis_product(n_terms): """ # 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 + n = np.arange(1, n_terms + 1) + term = term = (4 * n ** 2) / (4 * n ** 2 - 1) + product = np.prod(term) + + return 2.0 * product diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..86f3f5aa 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 @@ -45,6 +45,8 @@ def fit(self, X, y): self.n_features_in_ = X.shape[1] # XXX fix + self.X_ = X + self.y_ = y return self def predict(self, X): @@ -60,6 +62,10 @@ def predict(self, X): ) # XXX fix + for i, x_test in enumerate(X): + distances = np.sum((self.X_ - x_test)**2, axis=1) + closest_idx = np.argmin(distances) + y_pred[i] = self.y_[closest_idx] return y_pred def score(self, X, y): @@ -69,6 +75,5 @@ 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)