diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..545e1448 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -37,10 +37,19 @@ 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 2D") + i = 0 j = 0 - # TODO + for row in range(X.shape[0]): + for col in range(X.shape[1]): + if X[row, col] > X[i, j]: + i = row + j = col return i, j @@ -64,4 +73,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 + + prod = 1.0 + for n in range(1, n_terms + 1): + prod *= (4 * n ** 2) / (4 * n ** 2 - 1) + return 2 * prod diff --git a/sklearn_questions.py b/sklearn_questions.py index 948c2e54..ac76f03a 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -23,53 +23,82 @@ from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin from sklearn.utils.validation import check_X_y -from sklearn.utils.validation import check_array from sklearn.utils.validation import check_is_fitted from sklearn.utils.validation import validate_data from sklearn.utils.multiclass import check_classification_targets class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier. + + Predicts for each sample the label of the closest training sample, + using the Euclidean distance. + """ def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. - - And describe parameters + """Fit the classifier by storing the training data. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The training samples. + y : ndarray of shape (n_samples,) + The target labels of the training samples. + + Returns + ------- + self : OneNearestNeighbor + The fitted classifier. """ - X, y = check_X_y(X, y) + X, y = validate_data(self, X, y) check_classification_targets(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): - """Write docstring. + """Predict the label of each sample in X. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The samples to classify. - And describe parameters + Returns + ------- + y_pred : ndarray of shape (n_samples,) + The label of the closest training sample for each sample. """ check_is_fitted(self) - X = check_array(X) - y_pred = np.full( - shape=len(X), fill_value=self.classes_[0], - dtype=self.classes_.dtype - ) + X = validate_data(self, X, reset=False) - # XXX fix - return y_pred + # distances[i, k] = Euclidean distance between X[i] and X_train_[k] + diff = X[:, np.newaxis, :] - self.X_train_[np.newaxis, :, :] + distances = np.sqrt(np.sum(diff ** 2, axis=2)) - def score(self, X, y): - """Write docstring. + closest = np.argmin(distances, axis=1) + return self.y_train_[closest] - And describe parameters + def score(self, X, y): + """Compute the accuracy of the classifier on X and y. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The test samples. + y : ndarray of shape (n_samples,) + The true labels of the test samples. + + Returns + ------- + score : float + The fraction of samples correctly classified. """ X, y = check_X_y(X, y) y_pred = self.predict(X) - - # XXX fix - return y_pred.sum() + return np.mean(y_pred == y)