diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..60a8609f 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,11 +37,13 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ - i = 0 - 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") + flat_index = np.argmax(X, axis=None) + i, j = np.unravel_index(flat_index, X.shape) return i, j @@ -64,4 +66,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 + product = 1.0 + for n in range(1, n_terms + 1): + term1 = (2.0 * n) / (2.0 * n - 1.0) + term2 = (2.0 * n) / (2.0 * n + 1.0) + product = product * term1 * term2 + pi_approx = 2.0 * product + return pi_approx diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..03393491 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -28,8 +28,8 @@ from sklearn.utils.multiclass import check_classification_targets -class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass @@ -43,8 +43,8 @@ def fit(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): @@ -53,12 +53,20 @@ def predict(self, X): And describe parameters """ check_is_fitted(self) - X = check_array(X) + X = check_array(X, ensure_2d=True) + if X.shape[1] != self.n_features_in_: + raise ValueError( + f'X has {X.shape[1]} features, but {self.__class__.__name__} ' + f'is expecting {self.n_features_in_} features as input.' + ) y_pred = np.full( shape=len(X), fill_value=self.classes_[0], dtype=self.classes_.dtype ) - + for i, x_test in enumerate(X): + distances = np.sqrt(np.sum((self.X_ - x_test) ** 2, axis=1)) + nearest_idx = np.argmin(distances) + y_pred[i] = self.y_[nearest_idx] # XXX fix return y_pred @@ -69,6 +77,6 @@ def score(self, X, y): """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + accuracy = np.mean(y_pred == y) + return accuracy