diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..7de4bdcc 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 @@ -40,7 +41,21 @@ def max_index(X): i = 0 j = 0 - # TODO + if not isinstance(X, np.ndarray): + raise ValueError("Not a numpy array") + + if X.ndim != 2: + raise ValueError("Not a 2D array") + + n = X.shape[0] + m = X.shape[1] + max = 0 + for k in range(n): + for p in range(m): + if X[k][p] > max: + max = X[k][p] + i = k + j = p return i, j @@ -64,4 +79,19 @@ 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. + product = 1.0 + + if n_terms == 0: + return 1.0 + + n = 1 + while n <= n_terms: + numerator = 4 * n * n + denominator = (2 * n - 1) * (2 * n + 1) + product = product * (numerator / denominator) + n += 1 + + pi = product * 2 + + # approximation of order n_terms + return pi diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..aba5ad5b 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -19,6 +19,7 @@ for the methods you code and for the class. The docstring will be checked using `pydocstyle` that you can also call at the root of the repo. """ + import numpy as np from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin @@ -29,7 +30,7 @@ class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass @@ -44,7 +45,9 @@ def fit(self, X, y): self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - # XXX fix + self.X_train_ = X + self.y_train_ = y + return self def predict(self, X): @@ -54,13 +57,16 @@ 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 + + distances = np.sqrt( + np.sum(( + X[:, np.newaxis, :] - self.X_train_[np.newaxis, :, :] + ) ** 2, axis=2 + ) ) + nearest_indices = np.argmin(distances, axis=1) - # XXX fix - return y_pred + return self.y_train_[nearest_indices] def score(self, X, y): """Write docstring. @@ -70,5 +76,5 @@ def score(self, X, y): X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + accuracy = np.mean(y == y_pred) + return accuracy