diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..4845bc06 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -15,6 +15,7 @@ This will be enforced with `flake8`. You can check that there is no flake8 errors by calling `flake8` at the root of the repo. """ + import numpy as np @@ -37,12 +38,16 @@ 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("Input should be numpy array.") + if X.ndim != 2: + raise ValueError("Input should be 2D array.") # TODO + max_val = X.max() + i, j = np.where(X == max_val) - return i, j + return i[0], j[0] def wallis_product(n_terms): @@ -64,4 +69,12 @@ 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. + pi_approx = 1 + + if n_terms == 0: + return pi_approx + + for n in range(1, n_terms + 1): + pi_approx *= (4 * n**2) / (4 * n**2 - 1) + + return 2 * pi_approx diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..53b9efce 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 @@ -41,10 +41,11 @@ def fit(self, X, y): """ X, y = check_X_y(X, y) check_classification_targets(y) + self.X_ = X + self.y_ = y self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - # XXX fix return self def predict(self, X): @@ -54,12 +55,14 @@ def predict(self, X): """ check_is_fitted(self) X = check_array(X) - y_pred = np.full( - shape=len(X), fill_value=self.classes_[0], - dtype=self.classes_.dtype + + # euclidean distances between X and self.X_ + distances = np.linalg.norm( + self.X_[np.newaxis, :, :] - X[:, np.newaxis, :], axis=2 ) + nearest_indices = np.argmin(distances, axis=1) + y_pred = self.y_[nearest_indices] - # XXX fix 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)