diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..a975a805 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,10 +37,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 must be a numpy array.") - # TODO + if X.ndim != 2: + raise ValueError("Input array must be 2D.") + + # find the position + flat_idx = np.argmax(X) + # row and col + i, j = np.unravel_index(flat_idx, X.shape) return i, j @@ -62,6 +68,14 @@ 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. + if n_terms < 0: + raise ValueError("n_terms must be non-negative.") + + if n_terms == 0: + return 1.0 + + n = np.arange(1, n_terms + 1, dtype=float) + terms = (4 * n ** 2) / (4 * n ** 2 - 1) + product = np.prod(terms) + + return 2.0 * product diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..e4330346 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -28,47 +28,89 @@ from sklearn.utils.multiclass import check_classification_targets -class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): + """OneNearestNeighbor classifier. + + This classifier predicts the class of the closest training sample + in Euclidean distance. + """ def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. + """Fit the OneNearestNeighbor classifier. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training input samples. + + y : ndarray of shape (n_samples,) + Target labels for classification. - And describe parameters + Returns + ------- + self : object + Returns the fitted classifier. """ 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): - """Write docstring. + """Predict the class labels for samples in X. + + Parameters + ---------- + X : ndarray of shape (n_test_samples, n_features) + Samples to classify. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_test_samples,) + Predicted class labels. """ check_is_fitted(self) X = check_array(X) - y_pred = np.full( - shape=len(X), fill_value=self.classes_[0], - dtype=self.classes_.dtype - ) - # XXX fix - return y_pred + # check features + if X.shape[1] != self.n_features_in_: + raise ValueError( + "X has {} features, but OneNearestNeighbor is expecting {} " + "features as input".format(X.shape[1], self.n_features_in_) + ) + + # compute distances + distances = np.linalg.norm(X[:, None] - self.X_[None, :], axis=2) + + # nearest indices + nearest_idx = np.argmin(distances, axis=1) + + return self.y_[nearest_idx] def score(self, X, y): - """Write docstring. + """Return the accuracy of prediction on the given data. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Test samples. - And describe parameters + y : ndarray of shape (n_samples,) + True labels. + + Returns + ------- + score : float + Accuracy of the classifier. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)