From 658f2bd33dba33a7038dee649a8e66ba4d4905cc Mon Sep 17 00:00:00 2001 From: Ruben Castillo Date: Tue, 10 Nov 2026 23:55:43 +0100 Subject: [PATCH] Answered both numpy and sklearn questions --- numpy_questions.py | 17 ++++++++- sklearn_questions.py | 85 ++++++++++++++++++++++++++++++++++++++------ 2 files changed, 91 insertions(+), 11 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..af46ce69 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -41,6 +41,13 @@ def max_index(X): j = 0 # TODO + if not isinstance(X, np.ndarray): + raise ValueError('Input must be a numpy array') + if X.ndim != 2: + raise ValueError('Input array must be 2D') + + res = np.unravel_index(np.argmax(X), X.shape) + i, j = int(res[0]), int(res[1]) 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 + + arr = np.arange(n_terms) + 1 + arr = (4*arr**2)/(4*arr**2 - 1) + pi = arr.prod()*2 + + return pi diff --git a/sklearn_questions.py b/sklearn_questions.py index 948c2e54..8f8518b7 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -30,15 +30,46 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier. + + Predict for each sample the target of the closest training sample, + using the Euclidean distance. + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) + The unique class labels seen during `fit`. + n_features_in_ : int + The number of features seen during `fit`. + X_ : ndarray of shape (n_samples, n_features) + The training samples stored during `fit`. + y_ : ndarray of shape (n_samples,) + The training targets stored during `fit`. + """ def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. - - And describe parameters + """Fit the OneNearestNeighbor classifier. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The training samples. + y : ndarray of shape (n_samples,) + The target labels of the training samples. + + Returns + ------- + self : OneNearestNeighbor + The fitted classifier. + + Raises + ------ + ValueError + If `X` and `y` have inconsistent lengths, or if `y` is not a + valid classification target. """ X, y = check_X_y(X, y) check_classification_targets(y) @@ -46,12 +77,30 @@ def fit(self, X, 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 class labels for the provided samples. + + Each sample is assigned the target of its nearest training sample + in Euclidean distance. + + Parameters + ---------- + X : ndarray of shape (n_queries, n_features) + The samples to classify. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_queries,) + The predicted class label for each sample. + + Raises + ------ + NotFittedError + If the classifier has not been fitted yet. """ check_is_fitted(self) X = check_array(X) @@ -61,15 +110,31 @@ def predict(self, X): ) # XXX fix + X = validate_data(self, X, reset=False) + dist = X[:, None, :] - self.X_[None, :, :] + norm = np.linalg.norm(dist, axis=-1) + idx = np.argsort(norm, axis=-1)[:, 0] + y_pred = self.y_[idx] + return y_pred def score(self, X, y): - """Write docstring. - - And describe parameters + """Return the accuracy on the given test data and labels. + + Parameters + ---------- + X : ndarray of shape (n_queries, n_features) + The test samples. + y : ndarray of shape (n_queries,) + The true labels of the test samples. + + Returns + ------- + score : float + The fraction of samples correctly classified. """ X, y = check_X_y(X, y) y_pred = self.predict(X) # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)