From 38e8bca9b9a5ac98fcba46bff74c56db6f6a5bec Mon Sep 17 00:00:00 2001 From: Martin Lau <39431844+thatmartinlau@users.noreply.github.com> Date: Thu, 13 Nov 2025 15:22:10 +0100 Subject: [PATCH] First submission of Lab4 questions --- numpy_questions.py | 16 ++++++++- sklearn_questions.py | 80 +++++++++++++++++++++++++++++++++++--------- 2 files changed, 80 insertions(+), 16 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..44f794b8 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -41,6 +41,11 @@ def max_index(X): j = 0 # TODO + if not isinstance(X, np.ndarray) or X.ndim != 2: + raise ValueError("Input must be a 2D NumPy array") + + max_flat_index = np.argmax(X) + i, j = np.unravel_index(max_flat_index, X.shape) return i, j @@ -64,4 +69,13 @@ 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. + product = 1.0 + + if n_terms == 0: + return product + + for n in range(1, n_terms + 1): + numerator = 4 * n * n + product *= numerator / (numerator - 1) + + return 2 * product diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..94a7c88d 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,46 +29,96 @@ class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." + """One Nearest Neighbor classifier using Euclidean distance. + + This classifier assigns to each test sample the label of the + training point closest to it in Euclidean distance. + + Methods + ------- + fit(X, y) : + Store the training data. + + predict(X) : + Predict class labels for samples in X. + + score(X, y) : + Return the mean accuracy on the given test data and labels. + """ def __init__(self): # noqa: D107 + """Initialize the OneNearestNeighbor classifier.""" pass def fit(self, X, y): - """Write docstring. + """Fit the classifier from the training set (X, y). - 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 fitted estimator. """ X, y = check_X_y(X, y) check_classification_targets(y) + + self.X_train_ = X + self.y_train_ = y self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - # XXX fix return self def predict(self, X): - """Write docstring. + """Predict the class label for each sample in X. - And describe parameters + Parameters + ---------- + X : ndarray of shape (n_queries, n_features) + Query data. + + Returns + ------- + y_pred : ndarray of shape (n_queries,) + Predicted class labels. """ - check_is_fitted(self) X = check_array(X) - y_pred = np.full( - shape=len(X), fill_value=self.classes_[0], - dtype=self.classes_.dtype + check_is_fitted(self, ["X_train_", "y_train_"]) + + distances = np.linalg.norm( + X[:, np.newaxis] - self.X_train_, axis=2 ) - # XXX fix + nearest_indices = np.argmin(distances, axis=1) + + y_pred = self.y_train_[nearest_indices] + return y_pred def score(self, X, y): - """Write docstring. + """Return the mean accuracy on the given test data and labels. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Test data. + + y : ndarray of shape (n_samples,) + True labels for X. - And describe parameters + Returns + ------- + score : float + Mean accuracy of predictions. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)