From e49f08d5a5c3609183db98324561e9aa333fc1c5 Mon Sep 17 00:00:00 2001 From: Alice Finotti Date: Fri, 14 Nov 2025 15:34:25 +0100 Subject: [PATCH 1/9] Implement numpy and sklearn assignment --- numpy_questions.py | 27 +++++++++++++++++++-------- sklearn_questions.py | 17 ++++++++++------- 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..72645158 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,11 +37,12 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ - i = 0 - 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.") + flat_index = np.argmax(X) + i, j = np.unravel_index(flat_index, X.shape) return i, j @@ -62,6 +63,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 not isinstance(n_terms, int): + raise ValueError("n_terms must be an integer.") + if n_terms < 0: + raise ValueError("n_terms must be non-negative.") + if n_terms == 0: + pi = 1.0 + else: + product_terms = np.arange(1, n_terms + 1) + numerator = 4 * (product_terms ** 2) + denominator = numerator - 1 + pi = np.prod(numerator / denominator)*2 + + return pi diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..b01e02c5 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -28,7 +28,7 @@ from sklearn.utils.multiclass import check_classification_targets -class OneNearestNeighbor(BaseEstimator, ClassifierMixin): +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): "OneNearestNeighbor classifier." def __init__(self): # noqa: D107 @@ -43,8 +43,8 @@ def fit(self, 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): @@ -54,12 +54,16 @@ def predict(self, X): """ check_is_fitted(self) X = check_array(X) + X = self._validate_data(X, reset=False) y_pred = np.full( shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) + differences = (X[:, np.newaxis, :] - self.X_[np.newaxis, :, :]) + distances = np.sqrt(np.sum(differences) ** 2, axis=2) + nearest_indices = np.argmin(distances, axis=1) + y_pred = self.y_[nearest_indices] - # XXX fix return y_pred def score(self, X, y): @@ -69,6 +73,5 @@ def score(self, X, y): """ X, y = check_X_y(X, y) y_pred = self.predict(X) - - # XXX fix - return y_pred.sum() + score = np.sum(y_pred == y) + return score / len(y) From 16db27aa6f86153a9e255209505c236e55bd3035 Mon Sep 17 00:00:00 2001 From: Alice Finotti Date: Fri, 14 Nov 2025 15:38:23 +0100 Subject: [PATCH 2/9] Implement changes --- sklearn_questions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index b01e02c5..6478b636 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 @@ -60,7 +60,7 @@ def predict(self, X): dtype=self.classes_.dtype ) differences = (X[:, np.newaxis, :] - self.X_[np.newaxis, :, :]) - distances = np.sqrt(np.sum(differences) ** 2, axis=2) + distances = np.sqrt(np.sum(differences ** 2, axis=2)) nearest_indices = np.argmin(distances, axis=1) y_pred = self.y_[nearest_indices] From 26a80cb4d80d658a8b41d3d8b2f6899462ed33b4 Mon Sep 17 00:00:00 2001 From: Alice Finotti Date: Fri, 14 Nov 2025 16:02:35 +0100 Subject: [PATCH 3/9] Implement changes --- sklearn_questions.py | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 6478b636..c19c7118 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,15 +29,26 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - """OneNearestNeighbor classifier.""" + """One Nearest Neighbor classifier using Euclidean distance. + + This classifier assigns to each input sample the label of its closest + training sample, where closeness is measured using the Euclidean distance.""" def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. + """Fit the OneNearestNeighbor classifier from the training data. + + Parameters + X: ndarray of shape (n_samples, n_features) containing training data. + + y: ndarray of shape (n_samples,). + It contains target labels corresponding to the training samples. - And describe parameters + Returns + self : OneNearestNeighbor + The fitted classifier. """ X, y = check_X_y(X, y) check_classification_targets(y) @@ -48,9 +59,14 @@ def fit(self, X, y): return self def predict(self, X): - """Write docstring. + """Predict class labels for the input samples. - And describe parameters + Parameters + X: ndarray of shape (n_samples, n_features) containing input samples for which predictions are requested. + It must contain the same number of features as the training data. + + Returns + y_pred: ndarray of shape (n_samples,), containing predicted class labels for each input sample. """ check_is_fitted(self) X = check_array(X) @@ -67,9 +83,15 @@ def predict(self, X): return y_pred def score(self, X, y): - """Write docstring. + """Compute the accuracy of the classifier. + + Parameters + X: ndarray of shape (n_samples, n_features) containing test samples. + + y: array-like of shape (n_samples,) containing true labels for the test samples. - And describe parameters + Returns + accuracy: The fraction of correctly classified samples. """ X, y = check_X_y(X, y) y_pred = self.predict(X) From 9422008426acbff20fccf29cd26cc1014516fc28 Mon Sep 17 00:00:00 2001 From: Alice Finotti Date: Fri, 14 Nov 2025 16:12:12 +0100 Subject: [PATCH 4/9] Implement changes --- sklearn_questions.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index c19c7118..13e3574b 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -30,9 +30,9 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): """One Nearest Neighbor classifier using Euclidean distance. - This classifier assigns to each input sample the label of its closest - training sample, where closeness is measured using the Euclidean distance.""" + training sample, + where closeness is measured using the Euclidean distance.""" def __init__(self): # noqa: D107 pass @@ -42,8 +42,7 @@ def fit(self, X, y): Parameters X: ndarray of shape (n_samples, n_features) containing training data. - - y: ndarray of shape (n_samples,). + y: ndarray of shape (n_samples,). It contains target labels corresponding to the training samples. Returns @@ -62,11 +61,13 @@ def predict(self, X): """Predict class labels for the input samples. Parameters - X: ndarray of shape (n_samples, n_features) containing input samples for which predictions are requested. - It must contain the same number of features as the training data. + X: ndarray of shape (n_samples, n_features) + containing input samples for which predictions are requested. + It must contain the same number of features as the training data. Returns - y_pred: ndarray of shape (n_samples,), containing predicted class labels for each input sample. + y_pred: ndarray of shape (n_samples,), + containing predicted class labels for each input sample. """ check_is_fitted(self) X = check_array(X) @@ -87,8 +88,8 @@ def score(self, X, y): Parameters X: ndarray of shape (n_samples, n_features) containing test samples. - - y: array-like of shape (n_samples,) containing true labels for the test samples. + y: array-like of shape (n_samples,) + containing true labels for the test samples. Returns accuracy: The fraction of correctly classified samples. From cf97238ec7a6bdd346313b5944361d4f681bf3a4 Mon Sep 17 00:00:00 2001 From: Alice Finotti Date: Fri, 14 Nov 2025 16:14:39 +0100 Subject: [PATCH 5/9] Implement changes --- sklearn_questions.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 13e3574b..30f4b17f 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -19,6 +19,7 @@ for the methods you code and for the class. The docstring will be checked using `pydocstyle` that you can also call at the root of the repo. """ + import numpy as np from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin @@ -32,7 +33,8 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): """One Nearest Neighbor classifier using Euclidean distance. This classifier assigns to each input sample the label of its closest training sample, - where closeness is measured using the Euclidean distance.""" + where closeness is measured using the Euclidean distance. + """ def __init__(self): # noqa: D107 pass From d2bac94dfadc8be342ea11a35d0bf78e7c6bc5ca Mon Sep 17 00:00:00 2001 From: Alice Finotti Date: Fri, 14 Nov 2025 16:17:00 +0100 Subject: [PATCH 6/9] Implement changes --- sklearn_questions.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/sklearn_questions.py b/sklearn_questions.py index 30f4b17f..aa06089b 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -30,6 +30,7 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): + """One Nearest Neighbor classifier using Euclidean distance. This classifier assigns to each input sample the label of its closest training sample, @@ -40,6 +41,7 @@ def __init__(self): # noqa: D107 pass def fit(self, X, y): + """Fit the OneNearestNeighbor classifier from the training data. Parameters @@ -51,6 +53,7 @@ def fit(self, X, y): self : OneNearestNeighbor The fitted classifier. """ + X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) @@ -60,6 +63,7 @@ def fit(self, X, y): return self def predict(self, X): + """Predict class labels for the input samples. Parameters @@ -71,6 +75,7 @@ def predict(self, X): y_pred: ndarray of shape (n_samples,), containing predicted class labels for each input sample. """ + check_is_fitted(self) X = check_array(X) X = self._validate_data(X, reset=False) @@ -86,6 +91,7 @@ def predict(self, X): return y_pred def score(self, X, y): + """Compute the accuracy of the classifier. Parameters @@ -96,6 +102,7 @@ def score(self, X, y): Returns accuracy: The fraction of correctly classified samples. """ + X, y = check_X_y(X, y) y_pred = self.predict(X) score = np.sum(y_pred == y) From bde81dfd45fd47d7abdefbb317f78d160556fede Mon Sep 17 00:00:00 2001 From: Alice Finotti Date: Fri, 14 Nov 2025 16:20:06 +0100 Subject: [PATCH 7/9] Implement changes --- sklearn_questions.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index aa06089b..5b770df0 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -41,7 +41,6 @@ def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Fit the OneNearestNeighbor classifier from the training data. Parameters @@ -53,7 +52,6 @@ def fit(self, X, y): self : OneNearestNeighbor The fitted classifier. """ - X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) @@ -63,7 +61,6 @@ def fit(self, X, y): return self def predict(self, X): - """Predict class labels for the input samples. Parameters @@ -75,7 +72,6 @@ def predict(self, X): y_pred: ndarray of shape (n_samples,), containing predicted class labels for each input sample. """ - check_is_fitted(self) X = check_array(X) X = self._validate_data(X, reset=False) @@ -91,7 +87,6 @@ def predict(self, X): return y_pred def score(self, X, y): - """Compute the accuracy of the classifier. Parameters @@ -102,7 +97,6 @@ def score(self, X, y): Returns accuracy: The fraction of correctly classified samples. """ - X, y = check_X_y(X, y) y_pred = self.predict(X) score = np.sum(y_pred == y) From ada08c6b4590c0cdb76845645dd3ba4a8df4a58b Mon Sep 17 00:00:00 2001 From: Alice Finotti Date: Fri, 14 Nov 2025 16:21:56 +0100 Subject: [PATCH 8/9] Implement changes --- sklearn_questions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 5b770df0..d41f50ce 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -30,8 +30,8 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - """One Nearest Neighbor classifier using Euclidean distance. + This classifier assigns to each input sample the label of its closest training sample, where closeness is measured using the Euclidean distance. From 8c26be4419a30166111c5310d7e54bc384145898 Mon Sep 17 00:00:00 2001 From: Alice Finotti Date: Fri, 14 Nov 2025 16:25:28 +0100 Subject: [PATCH 9/9] Implement changes --- sklearn_questions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index d41f50ce..362fc58a 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -31,7 +31,7 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): """One Nearest Neighbor classifier using Euclidean distance. - + This classifier assigns to each input sample the label of its closest training sample, where closeness is measured using the Euclidean distance.