diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..e9d4ff11 Binary files /dev/null and b/.DS_Store differ diff --git a/github-assignment b/github-assignment new file mode 160000 index 00000000..769c2dd0 --- /dev/null +++ b/github-assignment @@ -0,0 +1 @@ +Subproject commit 769c2dd03019961072c98a6b9802aef4e14cfa67 diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..c16ec3dd 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,10 +37,15 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ + 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 array.") i = 0 j = 0 - # TODO + flat_index = np.argmax(X) + i, j = np.unravel_index(flat_index, X.shape) return i, j @@ -62,6 +67,12 @@ 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.0 + + for n in range(1, n_terms + 1): + product *= (4 * n**2) / (4 * n**2 - 1) + + pi = 2 * product + return pi diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..b8370f2a 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,46 +29,91 @@ class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." + """One Nearest Neighbor classifier. - def __init__(self): # noqa: D107 + This classifier predicts the label of the closest training sample + using the Euclidean distance. + """ + + def __init__(self): + """Initialize the OneNearestNeighbor classifier.""" pass def fit(self, X, y): - """Write docstring. + """Fit the classifier. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Class labels. - And describe parameters + Returns + ------- + self : object + The fitted classifier. """ X, y = check_X_y(X, y) check_classification_targets(y) + + self.X_ = X + self.y_ = y self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - # XXX fix return self def predict(self, X): - """Write docstring. + """Predict the closest label for each sample. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input samples. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Predicted class labels. """ - check_is_fitted(self) + check_is_fitted(self, ["X_", "y_", "n_features_in_"]) X = check_array(X) - y_pred = np.full( - shape=len(X), fill_value=self.classes_[0], - dtype=self.classes_.dtype - ) - # XXX fix + if X.shape[1] != self.n_features_in_: + raise ValueError( + "X has {} features, but OneNearestNeighbor was fitted with " + "{} features.".format(X.shape[1], self.n_features_in_) + ) + + n_samples = X.shape[0] + y_pred = np.empty(n_samples, dtype=self.y_.dtype) + + for i in range(n_samples): + # Compute Euclidean distances to all training samples + distances = np.linalg.norm(self.X_ - X[i], axis=1) + nn_index = np.argmin(distances) + y_pred[i] = self.y_[nn_index] + return y_pred def score(self, X, y): - """Write docstring. + """Return accuracy of the classifier. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Test samples. - And describe parameters + y : array-like of shape (n_samples,) + True labels. + + Returns + ------- + score : float + Accuracy (fraction of correct predictions). """ X, y = check_X_y(X, y) y_pred = self.predict(X) - - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)