diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..d2037499 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,12 +37,23 @@ 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("X must be a numpy array") + if X.ndim != 2: + raise ValueError("X must be a 2D numpy array") - # TODO + i_max = 0 + j_max = 0 + max_value = X[0, 0] - return i, j + for i in range(X.shape[0]): + for j in range(X.shape[1]): + if X[i, j] >= max_value: + max_value = X[i, j] + i_max = i + j_max = j + + return i_max, j_max def wallis_product(n_terms): @@ -62,6 +73,11 @@ 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 + for i in range(1, n_terms + 1): + numerator = 4 * i * i + denominator = numerator - 1 + product *= numerator / denominator + return 2.0 * product diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..44bb4a76 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -28,8 +28,12 @@ from sklearn.utils.multiclass import check_classification_targets -class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): + """OneNearestNeighbor classifier. + + A sample based on the class of its nearest neighbor in the training + set, using Euclidean distance. + """ def __init__(self): # noqa: D107 pass @@ -37,38 +41,70 @@ def __init__(self): # noqa: D107 def fit(self, X, y): """Write docstring. - And describe parameters + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training samples. + y : array-like of shape (n_samples,) + Target values (class labels). """ 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_train_ = X + self.y_train_ = y - # XXX fix return self def predict(self, X): """Write docstring. - And describe parameters + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Samples to predict. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Predicted class labels. """ 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 OneNearestNeighbor " + 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)): + distances = np.sqrt(np.sum((self.X_train_ - X[i]) ** 2, axis=1)) + nearest_idx = np.argmin(distances) + y_pred[i] = self.y_train_[nearest_idx] + return y_pred def score(self, X, y): """Write docstring. - And describe parameters + Parameters + ---------- + X : array of shape (n_samples, n_features) + Test samples. + y : array of shape (n_samples,) + True labels for X. + + Returns + ------- + score : float + Mean accuracy of self.predict(X) with respect to y. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)