diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..7a26ca59 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -41,8 +41,15 @@ def max_index(X): j = 0 # TODO + if not isinstance(X, np.ndarray): + raise ValueError("Input is not a numpy array.") + if X.ndim != 2: + raise ValueError("Input array is not 2D") - return i, j + flat_idx = np.argmax(X) + i, j = np.unravel_index(flat_idx, X.shape) + + return int(i), int(j) def wallis_product(n_terms): @@ -64,4 +71,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: + return 1.0 + + n = np.arange(1, n_terms + 1, dtype=float) + terms = (2 * n / (2 * n - 1)) * (2 * n / (2 * n + 1)) + product = np.prod(terms) + + return 2.0 * product diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..229a06ec 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 @@ -41,6 +41,8 @@ def fit(self, X, y): """ X, y = check_X_y(X, y) check_classification_targets(y) + self.X_train_ = X + self.y_train_ = y self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] @@ -54,12 +56,14 @@ def predict(self, X): """ check_is_fitted(self) X = check_array(X) - y_pred = np.full( - shape=len(X), fill_value=self.classes_[0], - dtype=self.classes_.dtype - ) + self._check_n_features(X, reset=False) + y_pred = np.empty(X.shape[0], dtype=self.classes_.dtype) # XXX fix + for i in range(len(X)): + distances = np.linalg.norm(self.X_train_ - X[i], axis=1) + nearest_index = np.argmin(distances) + y_pred[i] = self.y_train_[nearest_index] return y_pred def score(self, X, y): @@ -71,4 +75,4 @@ def score(self, X, y): y_pred = self.predict(X) # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)