diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..793a6b2e 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -40,8 +40,13 @@ def max_index(X): i = 0 j = 0 - # TODO - + if not isinstance(X, np.ndarray) or X.ndim != 2: + raise ValueError("X must be a 2D numpy array") + else: + for n in range(X.shape[0]): + for m in range(X.shape[1]): + if X[n, m] > X[i, j]: + i, j = n, m return i, j @@ -64,4 +69,11 @@ 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: + wallis = 1 + else: + wallis = 1 + for n in range(n_terms): + wallis *= (4 * (n+1)**2)/((4 * (n+1)**2) - 1) + wallis *= 2 + return wallis diff --git a/sklearn_questions.py b/sklearn_questions.py index 948c2e54..32676b12 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -30,7 +30,7 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass @@ -45,7 +45,8 @@ def fit(self, X, y): self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - # XXX fix + self.X_train_ = X + self.y_train_ = y return self def predict(self, X): @@ -55,12 +56,27 @@ def predict(self, X): """ check_is_fitted(self) X = check_array(X) + 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 ) - # XXX fix + for i in range(len(X)): + min_dist = None + index_min = None + x = X[i] + for j in range(len(self.X_train_)): + x_train = self.X_train_[j] + dist = np.linalg.norm(x - x_train) + if min_dist is None or dist < min_dist: + min_dist = dist + index_min = j + y_pred[i] = self.y_train_[index_min] return y_pred def score(self, X, y): @@ -70,6 +86,6 @@ def score(self, X, y): """ X, y = check_X_y(X, y) y_pred = self.predict(X) + accuracy = sum(y_pred == y) / len(y) - # XXX fix - return y_pred.sum() + return accuracy