From e9f9113c2bcfe54befe40be1a1f2ab43a9eafc10 Mon Sep 17 00:00:00 2001 From: aezacero Date: Sat, 15 Nov 2025 22:17:14 +0100 Subject: [PATCH 1/3] question answers --- numpy_questions.py | 19 +++++++++++-- sklearn_questions.py | 64 +++++++++++++++++++++++++++++++------------- 2 files changed, 63 insertions(+), 20 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..5ee62189 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -40,8 +40,15 @@ def max_index(X): i = 0 j = 0 - # TODO + # Raise ValueError + if not isinstance(X, np.ndarray) or X.ndim != 2: + raise ValueError("Input must be a 2D numpy array") + # Find max + max_val_index = np.argmax(X) # returns index of X flattened + + # Find index + i, j = np.unravel_index(max_val_index, X.shape) 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 + else: + cumprod = 1 + for n in range(1, n_terms + 1): + prod = (4 * (n ** 2)) / ((4 * (n ** 2)) - 1) + cumprod *= prod + return cumprod * 2 diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..1af30b73 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -22,53 +22,81 @@ 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 +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 based on X and y. + + Parameters + ---------- + X: array (n_samples, n_features). Training data. + + y: array (n_samples). Target data. + + Returns + ------- + self: object - And describe parameters """ - X, y = check_X_y(X, y) + X, y = validate_data(self, X, y, dtype=float) 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 the labels for each x based on Euclidean distance. + + Parameters + ---------- + X: array of test samples - And describe parameters + Returns + ------- + y_pred: array with shape (n_samples, ) of predicted labels """ check_is_fitted(self) - X = check_array(X) + X = validate_data(self, X, dtype=float, reset=False) y_pred = np.full( shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) - # XXX fix + # Compute distances + for i, x_test in enumerate(X): + distances = np.linalg.norm(self.X_ - x_test, axis=1) + idx = np.argmin(distances) + y_pred[i] = self.y_[idx] + return y_pred def score(self, X, y): - """Write docstring. + """Return the accuracy of the classifier. + + Parameters + ---------- + X: array (n_samples, n_features). Training data. + + y: array (n_samples). Target data. + + y_pred: array with shape (n_samples, ) of predicted labels - And describe parameters + Returns + ------- + accuracy: float, fraction of correct predictions. """ - X, y = check_X_y(X, y) + X, y = validate_data(self, X, y, dtype=float, reset=False) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y) From 1bde84f3735169157d9e2ce5e57beba0a75149f9 Mon Sep 17 00:00:00 2001 From: aezacero Date: Sat, 15 Nov 2025 22:25:49 +0100 Subject: [PATCH 2/3] Arnolfo Acero Part B --- sklearn_questions.py | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 1af30b73..fc2051ac 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -24,7 +24,8 @@ from sklearn.base import ClassifierMixin from sklearn.utils.validation import check_is_fitted from sklearn.utils.multiclass import check_classification_targets -from sklearn.utils.validation import validate_data +from sklearn.utils.validation import check_X_y +from sklearn.utils.validation import check_array class OneNearestNeighbor(ClassifierMixin, BaseEstimator): @@ -47,7 +48,7 @@ def fit(self, X, y): self: object """ - X, y = validate_data(self, X, y, dtype=float) + X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] @@ -67,7 +68,15 @@ def predict(self, X): y_pred: array with shape (n_samples, ) of predicted labels """ check_is_fitted(self) - X = validate_data(self, X, dtype=float, reset=False) + X = check_array(X) + + # Required by sklearn's check_estimator + if X.shape[1] != self.n_features_in_: + raise ValueError( + f"X has {X.shape[1]} features, but OneNearestNeighbor " + f"was fitted with {self.n_features_in_} features." + ) + y_pred = np.full( shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype @@ -96,7 +105,14 @@ def score(self, X, y): ------- accuracy: float, fraction of correct predictions. """ - X, y = validate_data(self, X, y, dtype=float, reset=False) - y_pred = self.predict(X) + X, y = check_X_y(X, y) - return np.mean(y_pred == y) + # Same feature check for consistency + if X.shape[1] != self.n_features_in_: + raise ValueError( + f"X has {X.shape[1]} features, but OneNearestNeighbor " + f"was fitted with {self.n_features_in_} features." + ) + + y_pred = self.predict(X) + return np.mean(y_pred == y) \ No newline at end of file From 1fecdca38f76fa849e370c0e27c981c6e1b8aac5 Mon Sep 17 00:00:00 2001 From: aezacero Date: Sat, 15 Nov 2025 22:28:23 +0100 Subject: [PATCH 3/3] 3 --- sklearn_questions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index fc2051ac..c1af974c 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -115,4 +115,4 @@ def score(self, X, y): ) y_pred = self.predict(X) - return np.mean(y_pred == y) \ No newline at end of file + return np.mean(y_pred == y)