diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..9e4a3cd7 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,10 +37,19 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ + if not isinstance(X, np.ndarray): + raise ValueError("Input must be a NumPy array.") + + if len(X.shape) != 2: + raise ValueError("Input should be a 2D numpy array.") + i = 0 j = 0 # TODO + i, j = np.unravel_index(np.argmax(X, axis=None), X.shape) + # i = int(ind[0]) + # j = int(ind[1]) return i, j @@ -64,4 +73,15 @@ 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 i in range(1, n_terms + 1): + numerator = 4 * i**2 + denominator = 4 * i**2 - 1 + product *= numerator / denominator + + pi = 2 * product + return pi diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..5f995168 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,28 +29,48 @@ class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. - - And describe parameters + """Fit the model given the training samples X and training targets y. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Array of the training samples. + y : ndarray of shape (n_samples,) + Array of the training targets. + + Returns + ------- + self : object + The fitted classifier. """ X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - # XXX fix + self.X_ = X + self.y_ = y + return self def predict(self, X): - """Write docstring. + """Find index of closest training sample and assign label to target. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Array of samples to predict. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Array of the predicted targets. """ check_is_fitted(self) X = check_array(X) @@ -59,16 +79,30 @@ def predict(self, X): dtype=self.classes_.dtype ) - # XXX fix + for i in range(X.shape[0]): + distances = np.linalg.norm(self.X_ - X[i, :], axis=1) + nearest_index = np.argmin(distances) + y_pred[i] = self.y_[nearest_index] return y_pred def score(self, X, y): - """Write docstring. - - And describe parameters + """Compute the number of correct predictions. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The test samples. + y : ndarray of shape (n_samples,) + The true labels. + + Returns + ------- + float + Accuracy of classifier. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + accuracy = np.mean(y_pred == y) + + return accuracy