From fa09a71790f78bd78f4e86f5a930ab1936432062 Mon Sep 17 00:00:00 2001 From: Anatole-JDM Date: Sun, 16 Nov 2025 23:53:50 +0100 Subject: [PATCH] Completed assignment: NumPy + OneNearestNeighbor implementation --- numpy_questions.py | 19 ++++++++++++-- sklearn_questions.py | 60 ++++++++++++++++++++++++++++++++++++-------- 2 files changed, 66 insertions(+), 13 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..886b2603 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -40,7 +40,14 @@ def max_index(X): i = 0 j = 0 - # TODO + if isinstance(X, np.ndarray) and X.ndim == 2: + index = np.argmax(X) + n_rows, n_cols = X.shape + + i = index // n_cols + j = index % n_cols + else: + raise ValueError("X must be a 2D numpy array") return i, j @@ -64,4 +71,12 @@ 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.0 + + result = 1.0 + for i in range(1, n_terms + 1): + result = result* (4 * i * i) / (4 * i * i - 1) + + return 2 * result diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..d204e010 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -35,22 +35,43 @@ def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. + """Fit the OneNearestNeighbor classifier. - And describe parameters + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training data. + + y : ndarray of shape (n_samples,) + Target labels. + + Returns + ------- + self : object + Returns the instance itself. """ 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 - return self + self.X_ = X + self.y_ = y + return self + def predict(self, X): - """Write docstring. + """Classifies the samples in X. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Input samples. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Predicted class labels. """ check_is_fitted(self) X = check_array(X) @@ -58,17 +79,34 @@ def predict(self, X): shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) + + + for i, x in enumerate(X): + neighbour = np.argmin(np.sqrt(((self.X_ - x) ** 2).sum(axis=1))) + y_pred[i] = self.y_[neighbour] - # XXX fix return y_pred + + def score(self, X, y): - """Write docstring. + """Computes the accuracy of the classifier. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Test samples. - And describe parameters + y : ndarray of shape (n_samples,) + True labels. + + Returns + ------- + score : float + The accuracy of predictions w.r.t. the true labels. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + return np.sum(y_pred == y)/len(y) +