From 897ffed14a5f1ddbfaabc37091e411986d3c84e1 Mon Sep 17 00:00:00 2001 From: christele geagea Date: Sun, 16 Nov 2025 16:54:07 +0100 Subject: [PATCH 1/4] Implement OneNearestNeighbor classifier --- sklearn_questions.py | 87 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 70 insertions(+), 17 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..e23971d3 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,46 +29,99 @@ class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." + """One-nearest-neighbor classifier. + + This classifier predicts the label of a sample using the label of the + closest training sample according to the Euclidean distance. + """ def __init__(self): # noqa: D107 + # Pas d'hyperparamètres pour ce modèle pass def fit(self, X, y): - """Write docstring. - - And describe parameters + """Fit the OneNearestNeighbor classifier. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + y : array-like of shape (n_samples,) + Target labels. + + Returns + ------- + self : OneNearestNeighbor + Fitted estimator. """ + # Vérifications standard scikit-learn X, y = check_X_y(X, y) check_classification_targets(y) + + # Attributs nécessaires pour scikit-learn self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - # XXX fix + # On mémorise les données d'entraînement + self.X_ = X + self.y_ = y + return self def predict(self, X): - """Write docstring. + """Predict class labels for the given test data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Test samples. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Predicted class labels for each sample 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 + # Vérifier que le nombre de features correspond + if X.shape[1] != self.n_features_in_: + raise ValueError("Number of features of X does not match training") + + n_samples_test = X.shape[0] + y_pred = np.empty(n_samples_test, dtype=self.y_.dtype) + + # Pour chaque point de test, on cherche le point d'entraînement + # le plus proche (distance euclidienne) et on copie son label. + for i in range(n_samples_test): + # différences entre x_i et tous les X_ de train + diffs = self.X_ - X[i] + # distances euclidiennes (norme L2) + dists = np.linalg.norm(diffs, axis=1) + # index du plus proche voisin + nearest_index = np.argmin(dists) + y_pred[i] = self.y_[nearest_index] + return y_pred def score(self, X, y): - """Write docstring. - - And describe parameters + """Return the mean accuracy on the given test data and labels. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Test samples. + y : array-like of shape (n_samples,) + True labels for X. + + Returns + ------- + score : float + Mean accuracy of predictions on X compared to y. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + # proportion de bonnes prédictions + return np.mean(y_pred == y) + From 0a0ff710250d6437bafdd3a1cfe75c721ad8fe76 Mon Sep 17 00:00:00 2001 From: christele geagea Date: Sun, 16 Nov 2025 17:03:34 +0100 Subject: [PATCH 2/4] Fix max_index and wallis_product implementations --- numpy_questions.py | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..05e45d59 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -19,49 +19,50 @@ def max_index(X): - """Return the index of the maximum in a numpy array. + """Return the index of the maximum in a 2D numpy array. Parameters ---------- - X : ndarray of shape (n_samples, n_features) - The input array. + X : ndarray of shape (n_rows, n_cols) + The input 2D array. Returns ------- (i, j) : tuple(int) - The row and columnd index of the maximum. + The row and column index of the maximum value in X. Raises ------ ValueError - If the input is not a numpy array or - if the shape is not 2D. + If the input is not a numpy array or is not 2D. """ - i = 0 - j = 0 + if not isinstance(X, np.ndarray): + raise ValueError("Input must be a numpy array.") + if X.ndim != 2: + raise ValueError("Input array must be 2-dimensional.") - # TODO + flat_index = np.argmax(X) + return 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. - See: - https://en.wikipedia.org/wiki/Wallis_product - Parameters ---------- n_terms : int - Number of steps in the Wallis product. Note that `n_terms=0` will - consider the product to be `1`. + Number of steps in the Wallis product. When n_terms = 0, the + product is defined as 1.0. Returns ------- pi : float - The approximation of order `n_terms` of pi using the Wallis product. + Approximation 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 + + k = np.arange(1, n_terms + 1, dtype=float) + factors = (4 * k**2) / (4 * k**2 - 1) + return float(np.prod(factors)) From ed7130a55c242a95c28f28b51f79704ef5d41e25 Mon Sep 17 00:00:00 2001 From: christele geagea Date: Sun, 16 Nov 2025 17:12:02 +0100 Subject: [PATCH 3/4] Fix flake8 blank line issues --- numpy_questions.py | 1 - sklearn_questions.py | 2 -- 2 files changed, 3 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 05e45d59..0ab9d791 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -45,7 +45,6 @@ def max_index(X): return np.unravel_index(flat_index, X.shape) - def wallis_product(n_terms): """Implement the Wallis product to compute an approximation of pi. diff --git a/sklearn_questions.py b/sklearn_questions.py index e23971d3..5205a0ab 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -121,7 +121,5 @@ def score(self, X, y): """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # proportion de bonnes prédictions return np.mean(y_pred == y) - From 29e84bd2ddf813a0248b3ad4e4fb86842449d07e Mon Sep 17 00:00:00 2001 From: christele geagea Date: Sun, 16 Nov 2025 17:17:15 +0100 Subject: [PATCH 4/4] Correct Wallis product to approximate pi --- numpy_questions.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/numpy_questions.py b/numpy_questions.py index 0ab9d791..534476ff 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -64,4 +64,5 @@ def wallis_product(n_terms): k = np.arange(1, n_terms + 1, dtype=float) factors = (4 * k**2) / (4 * k**2 - 1) - return float(np.prod(factors)) + product = np.prod(factors) + return float(2 * product)