From 15bf85344590ae72e89360a0f25c8a1c89f45a3f Mon Sep 17 00:00:00 2001 From: melo0430 <114441213+melo0430@users.noreply.github.com> Date: Thu, 13 Nov 2025 16:27:56 +0100 Subject: [PATCH 1/2] Complete assignment by Hou Litong --- numpy_questions.py | 28 ++++++++++++----- sklearn_questions.py | 75 ++++++++++++++++++++++++++++++-------------- 2 files changed, 73 insertions(+), 30 deletions(-) diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..cf3febcb 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,12 +37,16 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ - i = 0 - j = 0 + if not isinstance(X, np.ndarray): + raise ValueError("Input must be a numpy array") - # TODO + if X.ndim != 2: + raise ValueError("Input must be 2D") - return i, j + flat_index = np.argmax(X) + i, j = np.unravel_index(flat_index, X.shape) + + return int(i), int(j) def wallis_product(n_terms): @@ -62,6 +66,16 @@ def wallis_product(n_terms): pi : float The approximation of order `n_terms` of pi using the Wallis product. """ - # 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 + + product = 1.0 + + for n in range(1, n_terms + 1): + numerator = (2 * n) ** 2 + denominator = (2 * n - 1) * (2 * n + 1) + product *= numerator / denominator + + pi = 2 * product + + return pi diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..6850fc25 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -23,52 +23,81 @@ 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. - - And describe parameters + """Store training data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + y : array-like of shape (n_samples,) + Target labels. + + Returns + ------- + self + Fitted estimator. """ - X, y = check_X_y(X, y) + X, y = validate_data(self, 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 class for each sample. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Samples to predict. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Predicted 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 - ) + X = validate_data(self, X, reset=False) + + y_pred = np.zeros(len(X), dtype=self.y_.dtype) + + for i in range(len(X)): + dists = np.sqrt(np.sum((self.X_ - X[i]) ** 2, axis=1)) + nearest = np.argmin(dists) + y_pred[i] = self.y_[nearest] - # XXX fix return y_pred def score(self, X, y): - """Write docstring. - - And describe parameters + """Compute classification accuracy. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Test samples. + y : array-like of shape (n_samples,) + True labels. + + Returns + ------- + accuracy : float + Fraction of correctly classified samples. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y) From 3ceb1f55eda5df1e17bccfe8baf66daf5053c831 Mon Sep 17 00:00:00 2001 From: melo0430 <114441213+melo0430@users.noreply.github.com> Date: Thu, 13 Nov 2025 16:54:40 +0100 Subject: [PATCH 2/2] Complete numpy and sklearn assignment - Hou Litong --- sklearn_questions.py | 57 ++++++++++++++++++++++---------------------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/sklearn_questions.py b/sklearn_questions.py index 6850fc25..08711db7 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -23,9 +23,9 @@ 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(ClassifierMixin, BaseEstimator): @@ -35,68 +35,69 @@ def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Store training data. + """Train the model by storing training data. Parameters ---------- - X : array-like of shape (n_samples, n_features) - Training data. - y : array-like of shape (n_samples,) - Target labels. + X : array-like, shape (n_samples, n_features) + Training samples. + y : array-like, shape (n_samples,) + Target values. Returns ------- - self - Fitted estimator. + self : object + Returns self. """ - X, y = validate_data(self, 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] self.X_ = X self.y_ = y - return self def predict(self, X): - """Predict class for each sample. + """Perform classification on test samples. Parameters ---------- - X : array-like of shape (n_samples, n_features) - Samples to predict. + X : array-like, shape (n_samples, n_features) + Test samples. Returns ------- - y_pred : ndarray of shape (n_samples,) - Predicted labels. + y_pred : array, shape (n_samples,) + Class labels for samples in X. """ check_is_fitted(self) - X = validate_data(self, X, reset=False) - + 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.zeros(len(X), dtype=self.y_.dtype) - for i in range(len(X)): - dists = np.sqrt(np.sum((self.X_ - X[i]) ** 2, axis=1)) - nearest = np.argmin(dists) - y_pred[i] = self.y_[nearest] - + distances = np.sqrt(np.sum((self.X_ - X[i]) ** 2, axis=1)) + nearest_idx = np.argmin(distances) + y_pred[i] = self.y_[nearest_idx] return y_pred def score(self, X, y): - """Compute classification accuracy. + """Calculate mean accuracy. Parameters ---------- - X : array-like of shape (n_samples, n_features) + X : array-like, shape (n_samples, n_features) Test samples. - y : array-like of shape (n_samples,) + y : array-like, shape (n_samples,) True labels. Returns ------- - accuracy : float - Fraction of correctly classified samples. + score : float + Mean accuracy. """ X, y = check_X_y(X, y) y_pred = self.predict(X)