From d1613c872f687b5fab8d823dd3ac16c0ae64249c Mon Sep 17 00:00:00 2001 From: abeldornbusch Date: Tue, 10 Nov 2026 16:16:37 +0100 Subject: [PATCH 1/4] Answers to the questions --- numpy_questions.py | 27 +++++++++++++++++++++------ sklearn_questions.py | 41 +++++++++++++++++++++++++---------------- 2 files changed, 46 insertions(+), 22 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..21187fef 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,15 +37,22 @@ 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 2-dimensional array") - # TODO + i, j = np.unravel_index(np.argmax(X), X.shape) return i, j +"""Method : checking for the errors, then converting the indices of the max +into a tuple ready to be returned""" + + def wallis_product(n_terms): + """Implement the Wallis product to compute an approximation of pi. See: @@ -62,6 +69,14 @@ 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 + else: + pi = 1 + for n in range(1, n_terms + 1): + pi = pi * (2*n)**2 / ((2*n - 1)*(2*n + 1)) + + return pi*2 + + +"""Method : 'for' loop in order to compute the desired product""" \ No newline at end of file diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..7d799c40 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -28,47 +28,56 @@ from sklearn.utils.multiclass import check_classification_targets -class OneNearestNeighbor(BaseEstimator, ClassifierMixin): +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): "OneNearestNeighbor classifier." def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. - - And describe parameters + """Here self corresponds to the particular + instance of the OneNearestNeighbor. + X is the observations with their features + y is the class of the observations """ 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_ = X + self.y_ = y return self - + def predict(self, X): - """Write docstring. - - And describe parameters + """We first raise an error + if X doesn't have the right dimensions. + + Then we compute the euclidean distance of + every observation to a given observation, + take the indice of the minimal one and + assign the class therefore predict to the indice of y_pred. """ check_is_fitted(self) 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 ) - - # XXX fix + for i in range(len(y_pred)): + y_pred[i] = self.y_[np.argmin(np.linalg.norm(self.X_ - X[i], axis = 1))] return y_pred def score(self, X, y): - """Write docstring. - - And describe parameters + """Here we compute the accuracy by comparing the prediction with the actual y """ X, y = check_X_y(X, y) y_pred = self.predict(X) + accuracy = np.mean(y_pred == y) - # XXX fix - return y_pred.sum() + return accuracy From bc86b580a1e1a29486d21c6655ce5acb4e298d11 Mon Sep 17 00:00:00 2001 From: abeldornbusch Date: Tue, 10 Nov 2026 16:33:12 +0100 Subject: [PATCH 2/4] Formatage PEP8 --- numpy_questions.py | 8 ++++---- sklearn_questions.py | 27 +++++++++++++-------------- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21187fef..3bc9bfc0 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 @@ -52,7 +53,6 @@ def max_index(X): def wallis_product(n_terms): - """Implement the Wallis product to compute an approximation of pi. See: @@ -74,9 +74,9 @@ def wallis_product(n_terms): else: pi = 1 for n in range(1, n_terms + 1): - pi = pi * (2*n)**2 / ((2*n - 1)*(2*n + 1)) + pi = pi * (2 * n) ** 2 / ((2 * n - 1) * (2 * n + 1)) - return pi*2 + return pi * 2 -"""Method : 'for' loop in order to compute the desired product""" \ No newline at end of file +"""Method : 'for' loop in order to compute the desired product""" diff --git a/sklearn_questions.py b/sklearn_questions.py index 7d799c40..f79a0273 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 @@ -35,7 +36,7 @@ def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Here self corresponds to the particular + """Here self corresponds to the particular instance of the OneNearestNeighbor. X is the observations with their features y is the class of the observations @@ -48,34 +49,32 @@ def fit(self, X, y): self.X_ = X self.y_ = y return self - + def predict(self, X): - """We first raise an error + """We first raise an error if X doesn't have the right dimensions. - - Then we compute the euclidean distance of + + Then we compute the euclidean distance of every observation to a given observation, - take the indice of the minimal one and + take the indice of the minimal one and assign the class therefore predict to the indice of y_pred. """ check_is_fitted(self) 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." - ) + 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 + shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) for i in range(len(y_pred)): - y_pred[i] = self.y_[np.argmin(np.linalg.norm(self.X_ - X[i], axis = 1))] + y_pred[i] = self.y_[np.argmin(np.linalg.norm(self.X_ - X[i], axis=1))] return y_pred def score(self, X, y): - """Here we compute the accuracy by comparing the prediction with the actual y - """ + """Here we compute the accuracy by comparing the prediction with the actual y""" X, y = check_X_y(X, y) y_pred = self.predict(X) accuracy = np.mean(y_pred == y) From 9fcd52feb67d544445bb12b2139100bd43d00e5f Mon Sep 17 00:00:00 2001 From: abeldornbusch Date: Tue, 10 Nov 2026 16:41:44 +0100 Subject: [PATCH 3/4] Formatage --- sklearn_questions.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index f79a0273..9643643b 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -20,6 +20,8 @@ `pydocstyle` that you can also call at the root of the repo. """ +"""One-nearest-neighbor classifier.""" + import numpy as np from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin @@ -29,13 +31,13 @@ from sklearn.utils.multiclass import check_classification_targets -class OneNearestNeighbor(ClassifierMixin, BaseEstimator): +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): # noqa: D300 "OneNearestNeighbor classifier." def __init__(self): # noqa: D107 pass - def fit(self, X, y): + def fit(self, X, y): # noqa: D205, D400, D401 """Here self corresponds to the particular instance of the OneNearestNeighbor. X is the observations with their features @@ -50,7 +52,7 @@ def fit(self, X, y): self.y_ = y return self - def predict(self, X): + def predict(self, X): # noqa: D205, D400, D401 """We first raise an error if X doesn't have the right dimensions. @@ -67,14 +69,16 @@ def predict(self, X): 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 + shape=len(X), fill_value=self.classes_[0], + dtype=self.classes_.dtype ) for i in range(len(y_pred)): - y_pred[i] = self.y_[np.argmin(np.linalg.norm(self.X_ - X[i], axis=1))] + distances = np.linalg.norm(self.X_ - X[i], axis=1) + y_pred[i] = self.y_[np.argmin(distances)] return y_pred - def score(self, X, y): - """Here we compute the accuracy by comparing the prediction with the actual y""" + def score(self, X, y): # noqa: D400, D401 + """Here we compute the accuracy by comparing the prediction with the actual y""" # noqa: E501 X, y = check_X_y(X, y) y_pred = self.predict(X) accuracy = np.mean(y_pred == y) From edd1e175b0faff69e73d3d6b286305ed2c1bc0bc Mon Sep 17 00:00:00 2001 From: abeldornbusch Date: Tue, 10 Nov 2026 16:50:08 +0100 Subject: [PATCH 4/4] formating --- numpy_questions.py | 6 ++---- sklearn_questions.py | 25 +++++++++++++------------ 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 3bc9bfc0..70593499 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,6 +37,8 @@ def max_index(X): ValueError If the input is not a numpy array or if the shape is not 2D. + Method : checking for the errors, then converting the indices of the max + into a tuple ready to be returned """ if not isinstance(X, np.ndarray): raise ValueError("X must be a numpy array") @@ -48,10 +50,6 @@ def max_index(X): return i, j -"""Method : checking for the errors, then converting the indices of the max -into a tuple ready to be returned""" - - 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 9643643b..3072145b 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -1,3 +1,13 @@ +"""One-nearest-neighbor classifier.""" + +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 + """Assignment - making a sklearn estimator. The goal of this assignment is to implement by yourself a scikit-learn @@ -20,16 +30,6 @@ `pydocstyle` that you can also call at the root of the repo. """ -"""One-nearest-neighbor classifier.""" - -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 - class OneNearestNeighbor(ClassifierMixin, BaseEstimator): # noqa: D300 "OneNearestNeighbor classifier." @@ -69,8 +69,9 @@ def predict(self, X): # noqa: D205, D400, D401 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 + shape=len(X), + fill_value=self.classes_[0], + dtype=self.classes_.dtype, ) for i in range(len(y_pred)): distances = np.linalg.norm(self.X_ - X[i], axis=1)