From 739812d58cd2c55a4682ed9febf932251fe96365 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Barbier?= Date: Thu, 13 Nov 2025 16:25:15 +0100 Subject: [PATCH 1/3] Complete numpy and sklearn assignments - implement max_index, wallis_product and OneNearestNeighbor classifier --- numpy_questions.py | 30 ++++++++++++++++++------ sklearn_questions.py | 54 +++++++++++++++++++++++++++++++++++--------- 2 files changed, 66 insertions(+), 18 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..d2037499 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,12 +37,23 @@ 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("X must be a numpy array") + if X.ndim != 2: + raise ValueError("X must be a 2D numpy array") - # TODO + i_max = 0 + j_max = 0 + max_value = X[0, 0] - return i, j + for i in range(X.shape[0]): + for j in range(X.shape[1]): + if X[i, j] >= max_value: + max_value = X[i, j] + i_max = i + j_max = j + + return i_max, j_max def wallis_product(n_terms): @@ -62,6 +73,11 @@ 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 + for i in range(1, n_terms + 1): + numerator = 4 * i * i + denominator = numerator - 1 + product *= numerator / denominator + return 2.0 * product diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..75cb93a8 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -23,13 +23,17 @@ 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.validation import validate_data from sklearn.utils.multiclass import check_classification_targets -class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): + """OneNearestNeighbor classifier. + + A sample based on the class of its nearest neighbor in the training + set, using Euclidean distance. + """ def __init__(self): # noqa: D107 pass @@ -37,38 +41,66 @@ def __init__(self): # noqa: D107 def fit(self, X, y): """Write docstring. - And describe parameters + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training samples. + y : array-like of shape (n_samples,) + Target values (class labels). """ 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 - # XXX fix return self def predict(self, X): """Write docstring. - And describe parameters + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Samples to predict. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Predicted class labels. """ check_is_fitted(self) - X = check_array(X) + X = validate_data(self, X, reset=False) y_pred = np.full( shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) - # XXX fix + for i in range(len(X)): + + distances = np.sqrt(np.sum((self.X_train_ - X[i]) ** 2, axis=1)) + nearest_idx = np.argmin(distances) + y_pred[i] = self.y_train_[nearest_idx] + return y_pred def score(self, X, y): """Write docstring. - And describe parameters + Parameters + ---------- + X : array of shape (n_samples, n_features) + Test samples. + y : array of shape (n_samples,) + True labels for X. + + Returns + ------- + score : float + Mean accuracy of self.predict(X) with respect to y. """ 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 84da31f2fc1b0c33883ed8aa131d548e9172a6aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Barbier?= Date: Thu, 13 Nov 2025 16:38:24 +0100 Subject: [PATCH 2/3] =?UTF-8?q?M=C3=A0J?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- klearn_questions.py | 35 +++++++++++++++++++++++++++++++++++ sklearn_questions.py | 10 +++++++--- 2 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 klearn_questions.py diff --git a/klearn_questions.py b/klearn_questions.py new file mode 100644 index 00000000..57e7b0f2 --- /dev/null +++ b/klearn_questions.py @@ -0,0 +1,35 @@ +diff --git a/sklearn_questions.py b/sklearn_questions.py +index 75cb93a..44bb4a7 100644 +--- a/sklearn_questions.py ++++ b/sklearn_questions.py +@@ -23,8 +23,8 @@ 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.validation import validate_data + from sklearn.utils.multiclass import check_classification_targets +  +  +@@ -71,14 +71,18 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): + Predicted class labels. + """ + check_is_fitted(self) +- X = validate_data(self, X, reset=False) ++ X = check_array(X) ++ 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.full( + shape=len(X), fill_value=self.classes_[0], + dtype=self.classes_.dtype + ) +  + for i in range(len(X)): +- + distances = np.sqrt(np.sum((self.X_train_ - X[i]) ** 2, axis=1)) + nearest_idx = np.argmin(distances) + y_pred[i] = self.y_train_[nearest_idx] diff --git a/sklearn_questions.py b/sklearn_questions.py index 75cb93a8..44bb4a76 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -23,8 +23,8 @@ 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.validation import validate_data from sklearn.utils.multiclass import check_classification_targets @@ -71,14 +71,18 @@ def predict(self, X): Predicted class labels. """ check_is_fitted(self) - X = validate_data(self, X, reset=False) + X = check_array(X) + 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.full( shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) for i in range(len(X)): - distances = np.sqrt(np.sum((self.X_train_ - X[i]) ** 2, axis=1)) nearest_idx = np.argmin(distances) y_pred[i] = self.y_train_[nearest_idx] From 223cffb2524f9627f9b42cb6395b6a2eaf37757b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Barbier?= Date: Thu, 13 Nov 2025 18:12:56 +0100 Subject: [PATCH 3/3] =?UTF-8?q?M=C3=A0J?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- klearn_questions.py | 35 ----------------------------------- 1 file changed, 35 deletions(-) delete mode 100644 klearn_questions.py diff --git a/klearn_questions.py b/klearn_questions.py deleted file mode 100644 index 57e7b0f2..00000000 --- a/klearn_questions.py +++ /dev/null @@ -1,35 +0,0 @@ -diff --git a/sklearn_questions.py b/sklearn_questions.py -index 75cb93a..44bb4a7 100644 ---- a/sklearn_questions.py -+++ b/sklearn_questions.py -@@ -23,8 +23,8 @@ 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.validation import validate_data - from sklearn.utils.multiclass import check_classification_targets -  -  -@@ -71,14 +71,18 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - Predicted class labels. - """ - check_is_fitted(self) -- X = validate_data(self, X, reset=False) -+ X = check_array(X) -+ 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.full( - shape=len(X), fill_value=self.classes_[0], - dtype=self.classes_.dtype - ) -  - for i in range(len(X)): -- - distances = np.sqrt(np.sum((self.X_train_ - X[i]) ** 2, axis=1)) - nearest_idx = np.argmin(distances) - y_pred[i] = self.y_train_[nearest_idx]