diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..5f76a261 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "black-formatter.args": ["--line-length", "79"], + "editor.rulers": [79] +} \ No newline at end of file diff --git a/numpy_questions.py b/numpy_questions.py index 21fcec4b..7c89093d 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 @@ -37,12 +38,22 @@ def max_index(X): If the input is not a numpy array or if the shape is not 2D. """ + if X is None: + raise ValueError + if not isinstance(X, np.ndarray): + raise ValueError + if len(X.shape) != 2: + raise ValueError + i = 0 j = 0 - # TODO + max = np.max(X) + (i, j), *_ = np.argwhere(X == max) + return (i, j) - return i, j + +# print(max_index(np.array([[0, 1], [2, 0]]))) def wallis_product(n_terms): @@ -64,4 +75,19 @@ 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 + + indices = np.arange(1, n_terms + 1) + x = 4 * indices**2 + factors = x / (x - 1) + prod = 2 * np.prod(factors) + return prod + + +# print(wallis_product(0)) +# print(wallis_product(1)) +# print(wallis_product(10)) +# print(wallis_product(10000)) +# print(wallis_product(20000)) diff --git a/sklearn_questions.py b/sklearn_questions.py index 948c2e54..4351bbad 100644 --- a/sklearn_questions.py +++ b/sklearn_questions.py @@ -19,6 +19,7 @@ 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 @@ -30,46 +31,120 @@ class OneNearestNeighbor(ClassifierMixin, BaseEstimator): - "OneNearestNeighbor classifier." + """OneNearestNeighbor classifier.""" def __init__(self): # noqa: D107 pass def fit(self, X, y): - """Write docstring. + """Fit the model. But for KNN (Here 1NN) there is no real fit to do. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input array. + + y : ndarray of shape (n_samples,) + The output array. - And describe parameters + Returns + ------- + self """ + X, y = validate_data(self, X, y) + 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 + """Return the class predicted. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input array. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + The output array. + + Raises + ------ + ValueError + if the shape is not 2D. """ check_is_fitted(self) + X = validate_data(self, X, reset=False) + + if len(X.shape) != 2: + raise ValueError + X = check_array(X) + # if self.n_features_in_ != X.shape[1]: + # raise ValueError + 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 + # pour chaque ligne (point) de X + # calculer la distance entre le point et tous les autres points. + # garder le point avec la plus petit distance + # retourner sa classe + + # le faire si possible avec le broadcasting + + # la distance avec le broadcasting mais que pour le premier point + np.sqrt(np.sum((self.X_train_ - X[0]) ** 2, axis=1)) + + # On veut un tableau (n_test,n_train,p) le p est le même car on a le + # même nombre de features + + # On a un tableau ou la distance au carré entre le point i et j est + # à la case (i,j) + # J'ai enlevé le sqrt puisque que pas utile pour les comparaisons + distances = np.sum( + (self.X_train_[None, :, :] - X[:, None, :]) ** 2, axis=2 + ) + + # Maintenant on veut trouver pour chaque ligne le point + # avec la plus petite distance + closest_points = np.argmin(distances, axis=1) + # Ça retourne pour chaque ligne l'indice de la plus petite distance + y_pred = self.y_train_[ + closest_points + ] # et ça ça doit être les classes de ces points. + return y_pred def score(self, X, y): - """Write docstring. + """Return the score. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input array. + y : ndarray of shape (n_samples,) + The output array. + + Returns + ------- + score : float, + the accuracy of the model between 0 and 1. - And describe parameters """ X, y = check_X_y(X, y) y_pred = self.predict(X) + score = np.sum(y_pred == y) / len(y) - # XXX fix - return y_pred.sum() + return score