diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..b421172b 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,15 @@ 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 must be a numpy array.") + if X.ndim != 2: + raise ValueError("Input array must be 2D.") - # 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): @@ -62,6 +66,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_approx = 1 + + if n_terms == 0: + return pi_approx + + for k in range(1, n_terms + 1): + pi_approx *= (4 * k**2) / (4 * k**2 - 1) + + return 2 * pi_approx diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..db87bc09 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 @@ -39,12 +40,30 @@ def fit(self, X, y): And describe parameters """ + """Fit the model on the training data. + + Parameters + ---------- + X : array of shape (n_samples, n_features) + These are the training samples. These are the points the model will + use later to find the nearest neighbor. + + y : array of shape (n_samples,) + These are the labels for each training sample in X. This is what we + want to predict when we see new data. + + Returns + ------- + self + The model itself, following the sklearn convention. + """ 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): @@ -52,14 +71,29 @@ def predict(self, X): And describe parameters """ + """Predict labels for the input samples. + + Parameters + ---------- + X : array of shape (n_samples, n_features) + These are the data points we want to classify. They must have the + same number of features as the training data. + + + Returns + ------- + y_pred : array of shape (n_samples,) + These are the predicted labels. For each sample, we look at the + closest point in the training set and use its label. + + """ + 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.linalg.norm(self.X_[None, :, :] - X[:, None, :], axis=2) + nearest_idx = np.argmin(distances, axis=1) + y_pred = self.y_[nearest_idx] - # XXX fix return y_pred def score(self, X, y): @@ -67,8 +101,22 @@ def score(self, X, y): And describe parameters """ + """Compute the accuracy of the model. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The samples used to test the model. + + y : array-like of shape (n_samples,) + The true labels, so we can compare them with what we predicted. + + Returns + ------- + score : float + The accuracy of the predictions, between 0 and 1. + """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)