From dfa4dfacd23cfa7ff2669b862e99102e41fe7feb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Cliseteyssier2703=E2=80=9D?= <“liseteyssier@gmail.com”> Date: Tue, 10 Nov 2026 16:48:51 +0100 Subject: [PATCH 1/8] Finish numpy and sklearn questions --- numpy_questions.py | 25 +++++++++++++++-- sklearn_questions.py | 66 +++++++++++++++++++++++++++++++++++--------- 2 files changed, 75 insertions(+), 16 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..2cf1cb9e 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,10 +37,20 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ + if not isinstance(X, np.ndarray): + raise ValueError("Input is not a numpy array") + if X.ndim != 2: + raise ValueError("Shape of Array is not 2D") + i = 0 j = 0 - - # TODO + cur_max = X[0, 0] + for a in range(X.shape[0]): + for b in range(X.shape[1]): + if X[a, b] > cur_max: + cur_max = X[a, b] + i = a + j = b return i, j @@ -62,6 +72,15 @@ def wallis_product(n_terms): pi : float The approximation of order `n_terms` of pi using the Wallis product. """ + product = 1 + if n_terms == 0: + return 1 + + for x in range(1, n_terms + 1): + curr_factor = 4 * (x**2) / (4 * (x**2) - 1) + product = product * curr_factor + # XXX : The n_terms is an int that corresponds to the number of # terms in the product. For example 10000. - return 0. + + return product * 2 diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..fdfff56a 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -28,47 +28,87 @@ 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 + """Return the fitted classifier based on training data. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The training data. + y : ndarray of shape (n_samples,) + The target labels. + + Returns + ------- + self : OneNearestNeighbor + The fitted classifier. """ 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. + """Predict labels using nearest training sample. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The samples to classify. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_samples,) + The predicted labels for input sample. """ 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 ) + for i, sample in enumerate(X): + differences = self.X_ - sample + distances = np.sqrt(np.sum(differences ** 2, axis=1)) + min_index = np.argmin(distances) + y_pred[i] = self.y_[min_index] - # XXX fix return y_pred def score(self, X, y): - """Write docstring. - - And describe parameters + """Measure accuracy of predictions. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The samples to evaluate. + y : ndarray of shape (n_samples,) + The correct labels. + + Returns + ------- + accuracy : float + The proportion of correctly classified samples. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + accuracy = sum(y_pred == y) / len(y) + return accuracy From 724a49727cd6867f285d51a44f72d03600b2671f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Cliseteyssier2703=E2=80=9D?= <“liseteyssier@gmail.com”> Date: Tue, 10 Nov 2026 17:31:36 +0100 Subject: [PATCH 2/8] Update sklearn classifier --- sklearn_questions.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sklearn_questions.py b/sklearn_questions.py index fdfff56a..d0ae12b8 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -26,6 +26,7 @@ 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): @@ -49,6 +50,7 @@ def fit(self, X, y): self : OneNearestNeighbor The fitted classifier. """ + X, y = validate_data(self, X, y, reset=True) X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) From f378916eba6c1444aa58a87f03c91709b88f1048 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Cliseteyssier2703=E2=80=9D?= <“liseteyssier@gmail.com”> Date: Tue, 10 Nov 2026 17:38:53 +0100 Subject: [PATCH 3/8] Update sklearn classifier --- sklearn_questions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index d0ae12b8..024b1175 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -51,7 +51,7 @@ def fit(self, X, y): The fitted classifier. """ X, y = validate_data(self, X, y, reset=True) - X, y = check_X_y(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] From 6b26f0cb490d6e5086e442050c121801903883be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Cliseteyssier2703=E2=80=9D?= <“liseteyssier@gmail.com”> Date: Tue, 10 Nov 2026 17:45:46 +0100 Subject: [PATCH 4/8] Update sklearn classifier --- sklearn_questions.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 024b1175..f795c374 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -26,8 +26,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): "OneNearestNeighbor classifier." @@ -50,8 +48,7 @@ def fit(self, X, y): self : OneNearestNeighbor The fitted classifier. """ - X, y = validate_data(self, X, y, reset=True) - # X, y = check_X_y(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] From 82a98721842ad7c71737729b4104ab1c8f2662df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Cliseteyssier2703=E2=80=9D?= <“liseteyssier@gmail.com”> Date: Tue, 10 Nov 2026 17:53:58 +0100 Subject: [PATCH 5/8] Fix Code Style Check --- sklearn_questions.py | 1 - 1 file changed, 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index be4f0dd2..f795c374 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -25,7 +25,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 class OneNearestNeighbor(ClassifierMixin, BaseEstimator): From 948b7474b1d0d5f4181ef6f5103f5a8fe5166dfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Cliseteyssier2703=E2=80=9D?= <“liseteyssier@gmail.com”> Date: Tue, 10 Nov 2026 17:59:07 +0100 Subject: [PATCH 6/8] Fix Code Style Check --- sklearn_questions.py | 1 + 1 file changed, 1 insertion(+) diff --git a/sklearn_questions.py b/sklearn_questions.py index f795c374..fdfff56a 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -27,6 +27,7 @@ from sklearn.utils.validation import check_is_fitted from sklearn.utils.multiclass import check_classification_targets + class OneNearestNeighbor(ClassifierMixin, BaseEstimator): "OneNearestNeighbor classifier." From d60891e1b97f2e5bf8a9e1afa110d17915712f21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Cliseteyssier2703=E2=80=9D?= <“liseteyssier@gmail.com”> Date: Tue, 10 Nov 2026 18:09:34 +0100 Subject: [PATCH 7/8] Fix Code Style Check --- sklearn_questions.py | 64 ++++++++++++++++++++++---------------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index fdfff56a..361275db 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,7 +29,7 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass @@ -37,17 +37,17 @@ def __init__(self): # noqa: D107 def fit(self, X, y): """Return the fitted classifier based on training data. - Parameters - ---------- - X : ndarray of shape (n_samples, n_features) - The training data. - y : ndarray of shape (n_samples,) - The target labels. - - Returns - ------- - self : OneNearestNeighbor - The fitted classifier. + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The training data. + y : ndarray of shape (n_samples,) + The target labels. + + Returns + ------- + self : OneNearestNeighbor + The fitted classifier. """ X, y = check_X_y(X, y) check_classification_targets(y) @@ -60,17 +60,17 @@ def fit(self, X, y): return self def predict(self, X): - """Predict labels using nearest training sample. + """Predict labels using the nearest training sample. - Parameters - ---------- - X : ndarray of shape (n_samples, n_features) - The samples to classify. + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The samples to classify. - Returns - ------- - y_pred : ndarray of shape (n_samples,) - The predicted labels for input sample. + Returns + ------- + y_pred : ndarray of shape (n_samples,) + The predicted labels for input sample. """ check_is_fitted(self) X = check_array(X) @@ -95,17 +95,17 @@ def predict(self, X): def score(self, X, y): """Measure accuracy of predictions. - Parameters - ---------- - X : ndarray of shape (n_samples, n_features) - The samples to evaluate. - y : ndarray of shape (n_samples,) - The correct labels. - - Returns - ------- - accuracy : float - The proportion of correctly classified samples. + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The samples to evaluate. + y : ndarray of shape (n_samples,) + The correct labels. + + Returns + ------- + accuracy : float + The proportion of correctly classified samples. """ X, y = check_X_y(X, y) y_pred = self.predict(X) From f14a50e7cf866ea4c89ad9451a3f5dfed8bfd3a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Cliseteyssier2703=E2=80=9D?= <“liseteyssier@gmail.com”> Date: Tue, 10 Nov 2026 19:44:05 +0100 Subject: [PATCH 8/8] Adding Comments --- sklearn_questions.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 361275db..7801db57 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -26,6 +26,7 @@ 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): @@ -49,11 +50,13 @@ def fit(self, X, y): self : OneNearestNeighbor The fitted classifier. """ + # Check that X and y have compatible shapes and valid values. X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] + # Store the data self.X_ = X self.y_ = y @@ -74,19 +77,24 @@ def predict(self, X): """ 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" - ) + # Check that the data has the same features: + # Reads n_features_in_ back from the estimator + # And compares it with the number of columns in the new X + X = validate_data(self, X, reset=False) + y_pred = np.full( shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) for i, sample in enumerate(X): + # Subtract this sample from every training observation differences = self.X_ - sample + + # Find one distance per training observation distances = np.sqrt(np.sum(differences ** 2, axis=1)) + + # Select the nearest observation and copy its label min_index = np.argmin(distances) y_pred[i] = self.y_[min_index] @@ -110,5 +118,7 @@ def score(self, X, y): X, y = check_X_y(X, y) y_pred = self.predict(X) + # Calculate how accurate the predictions are + # In proportion to the observed classes accuracy = sum(y_pred == y) / len(y) return accuracy