From 84abd3fb2d06dcc61f5f1b287bd6c233a8d12c10 Mon Sep 17 00:00:00 2001 From: weichieh-chou Date: Thu, 13 Nov 2025 17:07:26 +0100 Subject: [PATCH 1/3] submit assignment - chou --- numpy_questions.py | 54 ++++++++++-------------------- sklearn_questions.py | 79 ++++++++++++++++++++++++++++++++++---------- 2 files changed, 79 insertions(+), 54 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..7e30412f 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -19,49 +19,31 @@ def max_index(X): - """Return the index of the maximum in a numpy array. + """Return the index of the maximum in a numpy array.""" + # Check input type + if not isinstance(X, np.ndarray): + raise ValueError("Input must be a numpy array.") - Parameters - ---------- - X : ndarray of shape (n_samples, n_features) - The input array. + # Check shape + if X.ndim != 2: + raise ValueError("Input must be a 2D array.") - Returns - ------- - (i, j) : tuple(int) - The row and columnd index of the maximum. - - Raises - ------ - ValueError - If the input is not a numpy array or - if the shape is not 2D. - """ - i = 0 - j = 0 - - # TODO + # Find the index of maximum + flat_index = np.argmax(X) + i, j = np.unravel_index(flat_index, X.shape) return i, j def wallis_product(n_terms): - """Implement the Wallis product to compute an approximation of pi. + """Implement the Wallis product to compute an approximation of pi.""" + if n_terms == 0: + return 1.0 # by definition - See: - https://en.wikipedia.org/wiki/Wallis_product + product = 1.0 + for n in range(1, n_terms + 1): + term = (4 * n * n) / (4 * n * n - 1) + product *= term - Parameters - ---------- - n_terms : int - Number of steps in the Wallis product. Note that `n_terms=0` will - consider the product to be `1`. + return 2 * product - Returns - ------- - 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. diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..03555720 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -27,48 +27,91 @@ from sklearn.utils.validation import check_is_fitted from sklearn.utils.multiclass import check_classification_targets - -class OneNearestNeighbor(BaseEstimator, ClassifierMixin): +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): "OneNearestNeighbor classifier." def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. + """Fit the OneNearestNeighbor classifier. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. - And describe parameters + y : array-like of shape (n_samples,) + Class labels. + + Returns + ------- + self : object + Fitted estimator. """ + # Validate X and y X, y = check_X_y(X, y) check_classification_targets(y) + + # Store training data + self.X_train_ = X + self.y_train_ = y + + # Required by sklearn API self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - # XXX fix return self def predict(self, X): - """Write docstring. + """Predict class labels using nearest neighbor. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input data. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Predicted 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 + # required by sklearn test: MUST match regex + if X.shape[1] != self.n_features_in_: + raise ValueError( + f"X has {X.shape[1]} features, but " + f"OneNearestNeighbor is expecting {self.n_features_in_} features as input" + ) + + y_pred = [] + + for x in X: + distances = np.linalg.norm(self.X_train_ - x, axis=1) + idx = np.argmin(distances) + y_pred.append(self.y_train_[idx]) + + return np.array(y_pred) + def score(self, X, y): - """Write docstring. + """Compute accuracy score. - And describe parameters + Parameters + ---------- + X : array-like + Input features. + + y : array-like + True labels. + + Returns + ------- + accuracy : float """ X, y = check_X_y(X, y) y_pred = self.predict(X) - - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y) From 63350286d91f3358a5040a2a308c63759a4089bb Mon Sep 17 00:00:00 2001 From: weichieh-chou Date: Thu, 13 Nov 2025 17:25:13 +0100 Subject: [PATCH 2/3] Fix flake8 issues --- numpy_questions.py | 2 -- sklearn_questions.py | 4 ++-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 7e30412f..dbc3af2e 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -36,7 +36,6 @@ def max_index(X): def wallis_product(n_terms): - """Implement the Wallis product to compute an approximation of pi.""" if n_terms == 0: return 1.0 # by definition @@ -46,4 +45,3 @@ def wallis_product(n_terms): product *= term return 2 * product - diff --git a/sklearn_questions.py b/sklearn_questions.py index 03555720..73e8b6ed 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -27,6 +27,7 @@ from sklearn.utils.validation import check_is_fitted from sklearn.utils.multiclass import check_classification_targets + class OneNearestNeighbor(ClassifierMixin, BaseEstimator): "OneNearestNeighbor classifier." @@ -84,7 +85,7 @@ def predict(self, X): if X.shape[1] != self.n_features_in_: raise ValueError( f"X has {X.shape[1]} features, but " - f"OneNearestNeighbor is expecting {self.n_features_in_} features as input" + f"expects {self.n_features_in_} features as input" ) y_pred = [] @@ -96,7 +97,6 @@ def predict(self, X): return np.array(y_pred) - def score(self, X, y): """Compute accuracy score. From 2f93f63edfc1cf7d790539ad0d53a400747f11fb Mon Sep 17 00:00:00 2001 From: weichieh-chou Date: Thu, 13 Nov 2025 17:31:47 +0100 Subject: [PATCH 3/3] Add missing docstrings and fix docstring style --- numpy_questions.py | 1 + sklearn_questions.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/numpy_questions.py b/numpy_questions.py index dbc3af2e..96c8820a 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -36,6 +36,7 @@ def max_index(X): def wallis_product(n_terms): + """Compute an approximation of pi using the Wallis product.""" if n_terms == 0: return 1.0 # by definition diff --git a/sklearn_questions.py b/sklearn_questions.py index 73e8b6ed..8f379d93 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,7 +29,7 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass