From 49f1dd048e925e286bd978083de84b0f5b7eff2f Mon Sep 17 00:00:00 2001 From: Camille Valenciennes Date: Tue, 10 Nov 2026 14:47:28 +0100 Subject: [PATCH 1/7] Numpy questions completed --- numpy_questions.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..922c8e84 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -40,7 +40,15 @@ def max_index(X): i = 0 j = 0 - # TODO + if not isinstance(X, np.ndarray): + raise ValueError("Only Numpy arrays are allowed") + elif X.ndim != 2: + raise ValueError("Only 2D arrays are allowed") + elif X.size == 0: + raise ValueError("Only non-empty arrays are allowed") + + i, j = np.unravel_index(X.argmax(), X.shape) + i, j = int(i), int(j) return i, j @@ -62,6 +70,12 @@ 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 + + squares = 4 * np.arange(1, n_terms+1) ** 2 + prod = np.prod(squares / (squares - 1)) + + return prod * 2 \ No newline at end of file From 7735bf8d3944596f0232603e3849ec6299d9cae5 Mon Sep 17 00:00:00 2001 From: Camille Valenciennes Date: Tue, 10 Nov 2026 16:03:40 +0100 Subject: [PATCH 2/7] Submission of numpy_questions.py and sklearn_questions.py --- numpy_questions.py | 6 ++-- sklearn_questions.py | 72 +++++++++++++++++++++++++++++++------------- 2 files changed, 54 insertions(+), 24 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 922c8e84..924edc3f 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -46,7 +46,7 @@ def max_index(X): raise ValueError("Only 2D arrays are allowed") elif X.size == 0: raise ValueError("Only non-empty arrays are allowed") - + i, j = np.unravel_index(X.argmax(), X.shape) i, j = int(i), int(j) @@ -77,5 +77,5 @@ def wallis_product(n_terms): squares = 4 * np.arange(1, n_terms+1) ** 2 prod = np.prod(squares / (squares - 1)) - - return prod * 2 \ No newline at end of file + + return prod * 2 diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..923317e4 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -22,53 +22,83 @@ import numpy as np from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin -from sklearn.utils.validation import check_X_y -from sklearn.utils.validation import check_array from sklearn.utils.validation import check_is_fitted from sklearn.utils.multiclass import check_classification_targets +from sklearn.utils.validation import validate_data -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 + """Fit the one-nearest-neighbor classifier. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The training samples. + y : ndarray of shape (n_samples, ) + The training labels. + + Returns + ------- + self : OneNearestNeighbor + The fitted estimator. """ - X, y = check_X_y(X, y) + X, y = validate_data(self, X, y) check_classification_targets(y) self.classes_ = np.unique(y) - self.n_features_in_ = X.shape[1] - - # XXX fix + self.X_train_ = X + self.y_train_ = y return self def predict(self, X): - """Write docstring. + """Predict the class of each sample of X. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The samples to classify. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (p_samples, ) + The predicted class of each sample of X. """ + X = validate_data(self, X, reset=False) 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 + diff = X[:, np.newaxis, :] - self.X_train_[np.newaxis, :, :] + dist = np.linalg.norm(diff, axis=2) + nearest = dist.argmin(axis=1) + y_pred = self.y_train_[nearest] + return y_pred def score(self, X, y): - """Write docstring. - - And describe parameters + """Return the accuracy of the classifier on (X,y). + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The test samples. + y : ndarray of shape (n_samples, ) + The test labels. + + Returns + ------- + score : float + The fraction of samples accurately classified. """ - X, y = check_X_y(X, y) + X = validate_data(self, X, reset=False) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + y_pred = y_pred == y + return y_pred.mean() From 3eb8e92fc8888fe5e795f7a7f2c2a9c3d70ff83e Mon Sep 17 00:00:00 2001 From: Camille Valenciennes Date: Tue, 10 Nov 2026 16:09:24 +0100 Subject: [PATCH 3/7] Conflict corrections sklearn_questions.py --- sklearn_questions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 923317e4..1c3faa14 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -28,7 +28,7 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - """OneNearestNeighbor classifier.""" + "OneNearestNeighbor classifier." def __init__(self): # noqa: D107 pass From c7c7cbf19001378a2a3bf06c6e52512091d6f443 Mon Sep 17 00:00:00 2001 From: Camille Valenciennes Date: Tue, 10 Nov 2026 16:27:55 +0100 Subject: [PATCH 4/7] Correction sklearn_questions.py --- sklearn_questions.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 1c3faa14..4754a26c 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -22,9 +22,10 @@ import numpy as np from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin +from sklearn.utils.validation import check_X_y +from sklearn.utils.validation import check_array from sklearn.utils.validation import check_is_fitted from sklearn.utils.multiclass import check_classification_targets -from sklearn.utils.validation import validate_data class OneNearestNeighbor(ClassifierMixin, BaseEstimator): @@ -48,9 +49,10 @@ def fit(self, X, y): self : OneNearestNeighbor The fitted estimator. """ - X, y = validate_data(self, X, y) + X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) + self.n_features_in_ = X.shape[1] self.X_train_ = X self.y_train_ = y return self @@ -68,13 +70,20 @@ def predict(self, X): y_pred : ndarray of shape (p_samples, ) The predicted class of each sample of X. """ - X = validate_data(self, X, reset=False) check_is_fitted(self) + X = check_array(X) y_pred = np.full( shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) + if X.shape[1] != self.n_features_in_: + raise ValueError( + f"X has {X.shape[1]} features, but " + f"{self.__class__.__name__} is expecting " + f"{self.n_features_in_} features as input" + ) + diff = X[:, np.newaxis, :] - self.X_train_[np.newaxis, :, :] dist = np.linalg.norm(diff, axis=2) nearest = dist.argmin(axis=1) @@ -97,7 +106,7 @@ def score(self, X, y): score : float The fraction of samples accurately classified. """ - X = validate_data(self, X, reset=False) + X, y = check_X_y(X, y) y_pred = self.predict(X) y_pred = y_pred == y From 80fdf3c4582c298b6941406652609f9c979a97a6 Mon Sep 17 00:00:00 2001 From: Camille Valenciennes Date: Tue, 10 Nov 2026 16:36:43 +0100 Subject: [PATCH 5/7] Debug From 7e6b90c1682cd9884bb6ed227e9e5e1d23432630 Mon Sep 17 00:00:00 2001 From: Camille Valenciennes Date: Tue, 10 Nov 2026 16:38:48 +0100 Subject: [PATCH 6/7] Attempt correction sklearn_questions.py --- sklearn_questions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 4754a26c..e9eb4ed1 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -28,7 +28,7 @@ from sklearn.utils.multiclass import check_classification_targets -class OneNearestNeighbor(ClassifierMixin, BaseEstimator): +class OneNearestNeighbor(BaseEstimator, ClassifierMixin): "OneNearestNeighbor classifier." def __init__(self): # noqa: D107 From a4fad42b77d89cda1c62f8cb720ef5135c81a273 Mon Sep 17 00:00:00 2001 From: Camille Valenciennes Date: Tue, 10 Nov 2026 17:08:23 +0100 Subject: [PATCH 7/7] Submission after reset --- sklearn_questions.py | 65 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 52 insertions(+), 13 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..e9eb4ed1 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -35,22 +35,40 @@ def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. - - And describe parameters + """Fit the one-nearest-neighbor classifier. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The training samples. + y : ndarray of shape (n_samples, ) + The training labels. + + Returns + ------- + self : OneNearestNeighbor + The fitted estimator. """ 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_train_ = X + self.y_train_ = y return self def predict(self, X): - """Write docstring. + """Predict the class of each sample of X. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The samples to classify. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (p_samples, ) + The predicted class of each sample of X. """ check_is_fitted(self) X = check_array(X) @@ -59,16 +77,37 @@ def predict(self, X): dtype=self.classes_.dtype ) - # XXX fix + if X.shape[1] != self.n_features_in_: + raise ValueError( + f"X has {X.shape[1]} features, but " + f"{self.__class__.__name__} is expecting " + f"{self.n_features_in_} features as input" + ) + + diff = X[:, np.newaxis, :] - self.X_train_[np.newaxis, :, :] + dist = np.linalg.norm(diff, axis=2) + nearest = dist.argmin(axis=1) + y_pred = self.y_train_[nearest] + return y_pred def score(self, X, y): - """Write docstring. - - And describe parameters + """Return the accuracy of the classifier on (X,y). + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The test samples. + y : ndarray of shape (n_samples, ) + The test labels. + + Returns + ------- + score : float + The fraction of samples accurately classified. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + y_pred = y_pred == y + return y_pred.mean()