diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..bbbf46e1 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -41,8 +41,15 @@ def max_index(X): j = 0 # TODO + if not isinstance(X, np.ndarray): + raise ValueError("Input is not a numpy array") + if X.ndim != 2: + raise ValueError("Input is not a 2D array") - return i, j + max_idx = np.unravel_index(np.argmax(X, axis=None), X.shape) + i, j = max_idx + + return (i, j) def wallis_product(n_terms): @@ -64,4 +71,9 @@ 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 + product = 1.0 + for n in range(1, n_terms + 1): + product *= (4 * n ** 2) / (4 * n ** 2 - 1) + return product * 2.0 diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..8008f718 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,15 +29,21 @@ class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. + """Fit the model to the training data. - And describe parameters + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input data. + + y : ndarray of shape (n_samples,) + The target labels. """ X, y = check_X_y(X, y) check_classification_targets(y) @@ -45,12 +51,22 @@ 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): - """Write docstring. + """Predict the class labels for the input data. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input data. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_samples,) + The predicted class labels. """ check_is_fitted(self) X = check_array(X) @@ -60,15 +76,29 @@ def predict(self, X): ) # XXX fix + for i, x in enumerate(X): + dists = np.linalg.norm(self.X_ - x, axis=1) + y_pred[i] = self.y_[np.argmin(dists)] return y_pred def score(self, X, y): - """Write docstring. + """Compute the accuracy of the model. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input data. + + y : ndarray of shape (n_samples,) + The true labels. - And describe parameters + Returns + ------- + score : float + The accuracy of the model. """ X, y = check_X_y(X, y) y_pred = self.predict(X) # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)