diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..9098e3b4 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -40,7 +40,12 @@ def max_index(X): i = 0 j = 0 - # TODO + if not isinstance(X, np.ndarray) or X.ndim != 2: + raise ValueError + + max_index = np.argmax(X) + i = max_index // X.shape[1] + j = max_index % X.shape[1] return i, j @@ -64,4 +69,14 @@ 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. + + product = 1 + for i in range(1, n_terms+1): + numerator = 4*i*i + denominator = numerator - 1 + product *= numerator/denominator + + if n_terms == 0: + return product + else: + return product*2 diff --git a/sklearn_questions.py b/sklearn_questions.py index f65038c6..ba945244 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -29,28 +29,50 @@ class OneNearestNeighbor(BaseEstimator, ClassifierMixin): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. + """Store training data. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input array of samples. + + y : ndarray of shape (n_samples,). + The input array of targets. + + Returns + ------- + self : OneNearestNeighbor + The fitted estimator. - And describe parameters """ 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. + """Predict the targets of training samples. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input array of test samples. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + The output array of predictions. - And describe parameters """ check_is_fitted(self) X = check_array(X) @@ -59,16 +81,31 @@ def predict(self, X): dtype=self.classes_.dtype ) - # XXX fix + for i, x in enumerate(X): + distances = np.linalg.norm(self._X_train - x, axis=1) + nearest_index = np.argmin(distances) + y_pred[i] = self._y_train[nearest_index] + return y_pred def score(self, X, y): - """Write docstring. + """Compute accuracy score of predictions. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input array of test samples. + + y : ndarray of shape (n_samples,). + The input array of targets. + + Returns + ------- + accuracy : float + Fraction of correctly classified samples. - And describe parameters """ X, y = check_X_y(X, y) y_pred = self.predict(X) - - # XXX fix - return y_pred.sum() + accuracy = (y_pred == y).mean() + return accuracy