diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..cf3febcb 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,12 +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 must be 2D") - return i, j + flat_index = np.argmax(X) + i, j = np.unravel_index(flat_index, X.shape) + + return int(i), int(j) def wallis_product(n_terms): @@ -62,6 +66,16 @@ 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: + return 1.0 + + product = 1.0 + + for n in range(1, n_terms + 1): + numerator = (2 * n) ** 2 + denominator = (2 * n - 1) * (2 * n + 1) + product *= numerator / denominator + + pi = 2 * product + + return pi diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..08711db7 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -28,47 +28,77 @@ from sklearn.utils.multiclass import check_classification_targets -class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. - - And describe parameters + """Train the model by storing training data. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training samples. + y : array-like, shape (n_samples,) + Target values. + + Returns + ------- + self : object + Returns self. """ 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. + """Perform classification on test samples. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Test samples. - And describe parameters + Returns + ------- + y_pred : array, shape (n_samples,) + Class labels for samples in 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 - ) - - # XXX fix + if X.shape[1] != self.n_features_in_: + raise ValueError( + f"X has {X.shape[1]} features, but OneNearestNeighbor " + f"is expecting {self.n_features_in_} features as input" + ) + y_pred = np.zeros(len(X), dtype=self.y_.dtype) + for i in range(len(X)): + distances = np.sqrt(np.sum((self.X_ - X[i]) ** 2, axis=1)) + nearest_idx = np.argmin(distances) + y_pred[i] = self.y_[nearest_idx] return y_pred def score(self, X, y): - """Write docstring. - - And describe parameters + """Calculate mean accuracy. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Test samples. + y : array-like, shape (n_samples,) + True labels. + + Returns + ------- + score : float + Mean accuracy. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)