diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..9a3301f8 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,12 +37,20 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ - i = 0 - j = 0 + # Check if input is a numpy array + if not isinstance(X, np.ndarray): + raise ValueError("Input must be a numpy array") - # TODO + # Check if array is 2D + if X.ndim != 2: + raise ValueError("Input must be a 2D array") - return i, j + # Find the index of the maximum value + # np.argmax returns the flattened index, so we use unravel_index + 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 +70,15 @@ 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. + # Wallis product: pi/2 = (2/1 * 2/3) * (4/3 * 4/5) * (6/5 * 6/7) * ... + # Or: pi/2 = product of (4n^2) / (4n^2 - 1) for n from 1 to n_terms + if n_terms == 0: + return 1.0 + + product = 1.0 + + for n in range(1, n_terms + 1): + product *= (4 * n**2) / (4 * n**2 - 1) + + # Multiply by 2 to get pi + return 2 * product diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..e827d503 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,7 +29,7 @@ class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass @@ -44,7 +44,10 @@ def fit(self, X, y): self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - # XXX fix + # Store training data + self.X_ = X + self.y_ = y + return self def predict(self, X): @@ -59,7 +62,15 @@ def predict(self, X): dtype=self.classes_.dtype ) - # XXX fix + # For each test sample, find the nearest training sample + for i, x in enumerate(X): + # Calculate Euclidean distances to all training samples + distances = np.sqrt(np.sum((self.X_ - x) ** 2, axis=1)) + # Find index of nearest neighbor + nearest_idx = np.argmin(distances) + # Assign the label of the nearest neighbor + y_pred[i] = self.y_[nearest_idx] + return y_pred def score(self, X, y): @@ -70,5 +81,7 @@ def score(self, X, y): X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + # Calculate accuracy: proportion of correct predictions + accuracy = np.mean(y_pred == y) + + return accuracy