diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..70593499 100644 --- a/numpy_questions.py +++ b/numpy_questions.py @@ -15,6 +15,7 @@ This will be enforced with `flake8`. You can check that there is no flake8 errors by calling `flake8` at the root of the repo. """ + import numpy as np @@ -36,11 +37,15 @@ def max_index(X): ValueError If the input is not a numpy array or if the shape is not 2D. + Method : checking for the errors, then converting the indices of the max + into a tuple ready to be returned """ - 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 2-dimensional array") - # TODO + i, j = np.unravel_index(np.argmax(X), X.shape) return i, j @@ -62,6 +67,14 @@ 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 + else: + pi = 1 + for n in range(1, n_terms + 1): + pi = pi * (2 * n) ** 2 / ((2 * n - 1) * (2 * n + 1)) + + return pi * 2 + + +"""Method : 'for' loop in order to compute the desired product""" diff --git a/sklearn_questions.py b/sklearn_questions.py index 948c2e54..3072145b 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -1,3 +1,13 @@ +"""One-nearest-neighbor classifier.""" + +import numpy as np +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.multiclass import check_classification_targets + """Assignment - making a sklearn estimator. The goal of this assignment is to implement by yourself a scikit-learn @@ -19,57 +29,59 @@ for the methods you code and for the class. The docstring will be checked using `pydocstyle` that you can also call at the root of the repo. """ -import numpy as np -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): +class OneNearestNeighbor(ClassifierMixin, BaseEstimator): # noqa: D300 "OneNearestNeighbor classifier." def __init__(self): # noqa: D107 pass - def fit(self, X, y): - """Write docstring. - - And describe parameters + def fit(self, X, y): # noqa: D205, D400, D401 + """Here self corresponds to the particular + instance of the OneNearestNeighbor. + X is the observations with their features + y is the class of the observations """ X, y = check_X_y(X, y) check_classification_targets(y) self.classes_ = np.unique(y) self.n_features_in_ = X.shape[1] - # XXX fix + self.X_ = X + self.y_ = y return self - def predict(self, X): - """Write docstring. + def predict(self, X): # noqa: D205, D400, D401 + """We first raise an error + if X doesn't have the right dimensions. - And describe parameters + Then we compute the euclidean distance of + every observation to a given observation, + take the indice of the minimal one and + assign the class therefore predict to the indice of y_pred. """ 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 + shape=len(X), + fill_value=self.classes_[0], + dtype=self.classes_.dtype, ) - - # XXX fix + for i in range(len(y_pred)): + distances = np.linalg.norm(self.X_ - X[i], axis=1) + y_pred[i] = self.y_[np.argmin(distances)] return y_pred - def score(self, X, y): - """Write docstring. - - And describe parameters - """ + def score(self, X, y): # noqa: D400, D401 + """Here we compute the accuracy by comparing the prediction with the actual y""" # noqa: E501 X, y = check_X_y(X, y) y_pred = self.predict(X) + accuracy = np.mean(y_pred == y) - # XXX fix - return y_pred.sum() + return accuracy