From 942e1d5b3a9423fc9d6411072fc7551cd8dc1af5 Mon Sep 17 00:00:00 2001 From: Simon Vital - PC Lenovo Date: Tue, 10 Nov 2026 20:04:45 +0100 Subject: [PATCH 1/8] questions --- numpy_questions.py | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..7c89093d 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -15,6 +15,7 @@ This will be enforced with `flake8`. You can check that there is no flake8 errors by calling `flake8` at the root of the repo. """ + import numpy as np @@ -37,12 +38,22 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ + if X is None: + raise ValueError + if not isinstance(X, np.ndarray): + raise ValueError + if len(X.shape) != 2: + raise ValueError + i = 0 j = 0 - # TODO + max = np.max(X) + (i, j), *_ = np.argwhere(X == max) + return (i, j) - return i, j + +# print(max_index(np.array([[0, 1], [2, 0]]))) def wallis_product(n_terms): @@ -64,4 +75,19 @@ def wallis_product(n_terms): """ # 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 + + indices = np.arange(1, n_terms + 1) + x = 4 * indices**2 + factors = x / (x - 1) + prod = 2 * np.prod(factors) + return prod + + +# print(wallis_product(0)) +# print(wallis_product(1)) +# print(wallis_product(10)) +# print(wallis_product(10000)) +# print(wallis_product(20000)) From eaf1ddccea7dbea1894d34005a23814c5bf0963a Mon Sep 17 00:00:00 2001 From: Simon Vital - PC Lenovo Date: Tue, 10 Nov 2026 20:04:55 +0100 Subject: [PATCH 2/8] questions 2 --- .vscode/settings.json | 4 ++ sklearn_questions.py | 103 ++++++++++++++++++++++++++++++++++++------ 2 files changed, 93 insertions(+), 14 deletions(-) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..5f76a261 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "black-formatter.args": ["--line-length", "79"], + "editor.rulers": [79] +} \ No newline at end of file diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..8094714a 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 @@ -26,49 +27,123 @@ 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. + """Fit the model + But for KNN (Here 1NN) there is no fit to do. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input array. + + y : ndarray of shape (n_samples,) + The output array. - And describe parameters + Returns + ------- + self """ + + 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 # XXX fix return self def predict(self, X): - """Write docstring. - - And describe parameters + """Returns the class predicted + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input array. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + The output array. + + Raises + ------ + ValueError + if the shape is not 2D. """ check_is_fitted(self) + X = validate_data(self, X, reset=False) + + if len(X.shape) != 2: + raise ValueError + X = check_array(X) + # if self.n_features_in_ != X.shape[1]: + # raise ValueError + y_pred = np.full( - shape=len(X), fill_value=self.classes_[0], - dtype=self.classes_.dtype + shape=len(X), + fill_value=self.classes_[0], + dtype=self.classes_.dtype, ) - # XXX fix + # pour chaque ligne (point) de X + # calculer la distance entre le point et tous les autres points. + # garder le point avec la plus petit distance + # retourner sa classe + + # le faire si possible avec le broadcasting + + # la distance avec le broadcasting mais que pour le premier point + d1 = np.sqrt(np.sum((self.X_train_ - X[0]) ** 2, axis=1)) + + # On veut un tableau (n_test,n_train,p) le p est le même car on a le même nombre de features + # avec ça, on a un tableau ou la distance au carré entre le point i et j est à la case (i,j) + # J'ai enlevé le sqrt puisque que pour les comparaisons ça n'est pas utile + distances = np.sum( + (self.X_train_[None, :, :] - X[:, None, :]) ** 2, axis=2 + ) + + # Maintenant on veut trouver pour chaque ligne le point avec la plus petite distance + closest_points = np.argmin( + distances, axis=1 + ) # normalement ça nous retourne pour chaque ligne l'indice de la plus petite distance + y_pred = self.y_train_[ + closest_points + ] # et ça ça doit être les classes de ces points. + return y_pred def score(self, X, y): - """Write docstring. + """Returns the score + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input array. + y : ndarray of shape (n_samples,) + The output array. + + Returns + ------- + score : float, + the accuracy of the model between 0 and 1. - And describe parameters """ X, y = check_X_y(X, y) y_pred = self.predict(X) + score = np.sum(y_pred == y) / len(y) - # XXX fix - return y_pred.sum() + return score From b12e20bcb7ce712aaab567fb5ac2780b18c30d2e Mon Sep 17 00:00:00 2001 From: Simon Vital - PC Lenovo Date: Tue, 10 Nov 2026 20:11:55 +0100 Subject: [PATCH 3/8] PEP 8 changes --- sklearn_questions.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 8094714a..19a1d7b9 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -107,19 +107,22 @@ def predict(self, X): # le faire si possible avec le broadcasting # la distance avec le broadcasting mais que pour le premier point - d1 = np.sqrt(np.sum((self.X_train_ - X[0]) ** 2, axis=1)) + np.sqrt(np.sum((self.X_train_ - X[0]) ** 2, axis=1)) - # On veut un tableau (n_test,n_train,p) le p est le même car on a le même nombre de features - # avec ça, on a un tableau ou la distance au carré entre le point i et j est à la case (i,j) - # J'ai enlevé le sqrt puisque que pour les comparaisons ça n'est pas utile + # On veut un tableau (n_test,n_train,p) le p est le même car on a le + # même nombre de features + + # On a un tableau ou la distance au carré entre le point i et j est + # à la case (i,j) + # J'ai enlevé le sqrt puisque que pas utile pour les comparaisons distances = np.sum( (self.X_train_[None, :, :] - X[:, None, :]) ** 2, axis=2 ) - # Maintenant on veut trouver pour chaque ligne le point avec la plus petite distance - closest_points = np.argmin( - distances, axis=1 - ) # normalement ça nous retourne pour chaque ligne l'indice de la plus petite distance + # Maintenant on veut trouver pour chaque ligne le point + # avec la plus petite distance + closest_points = np.argmin(distances, axis=1) + # Ça retourne pour chaque ligne l'indice de la plus petite distance y_pred = self.y_train_[ closest_points ] # et ça ça doit être les classes de ces points. From 948b505d2a60f8de0e706e3513c28562248b0fcd Mon Sep 17 00:00:00 2001 From: Simon Vital - PC Lenovo Date: Tue, 10 Nov 2026 20:18:04 +0100 Subject: [PATCH 4/8] improved docstyle --- sklearn_questions.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 19a1d7b9..e9a8f34a 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -37,8 +37,7 @@ def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Fit the model - But for KNN (Here 1NN) there is no fit to do. + """Fit the model. But for KNN (Here 1NN) there is no real fit to do. Parameters ---------- @@ -52,7 +51,6 @@ def fit(self, X, y): ------- self """ - X, y = validate_data(self, X, y) X, y = check_X_y(X, y) @@ -66,7 +64,7 @@ def fit(self, X, y): return self def predict(self, X): - """Returns the class predicted + """Return the class predicted. Parameters ---------- @@ -130,7 +128,7 @@ def predict(self, X): return y_pred def score(self, X, y): - """Returns the score + """Return the score. Parameters ---------- From 71307c8e4f1b3d21382d7ae861234091b872b3ec Mon Sep 17 00:00:00 2001 From: Simon Vital - PC Lenovo Date: Tue, 10 Nov 2026 20:23:51 +0100 Subject: [PATCH 5/8] remove unused import --- sklearn_questions.py | 1 - 1 file changed, 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index e9a8f34a..c1b0a23b 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -27,7 +27,6 @@ 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): From 52d2977c47d78cb83053320f0145686b82ca93d8 Mon Sep 17 00:00:00 2001 From: Simon Vital - PC Lenovo Date: Tue, 10 Nov 2026 20:25:11 +0100 Subject: [PATCH 6/8] removed unused validate import --- sklearn_questions.py | 1 - 1 file changed, 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index e6abc9cf..49e3e21a 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -26,7 +26,6 @@ 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 From 9de0c01038c631b82079636170684ac67953b394 Mon Sep 17 00:00:00 2001 From: Simon Vital - PC Lenovo Date: Tue, 10 Nov 2026 20:25:47 +0100 Subject: [PATCH 7/8] put it back --- sklearn_questions.py | 1 + 1 file changed, 1 insertion(+) diff --git a/sklearn_questions.py b/sklearn_questions.py index 49e3e21a..e6abc9cf 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -26,6 +26,7 @@ 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 From 8946acc9efd7f8327e6cfb9c2781e99613402ea3 Mon Sep 17 00:00:00 2001 From: Simon Vital - PC Lenovo Date: Tue, 10 Nov 2026 20:26:48 +0100 Subject: [PATCH 8/8] put triple quotes intead of simple --- sklearn_questions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index e6abc9cf..4351bbad 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -31,7 +31,7 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass