Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions numpy_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,15 @@ def max_index(X):
i = 0
j = 0

# TODO
if not isinstance(X, np.ndarray):
raise ValueError("Only Numpy arrays are allowed")
elif X.ndim != 2:
raise ValueError("Only 2D arrays are allowed")
elif X.size == 0:
raise ValueError("Only non-empty arrays are allowed")

i, j = np.unravel_index(X.argmax(), X.shape)
i, j = int(i), int(j)

return i, j

Expand All @@ -62,6 +70,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:
raise ValueError("n_terms must be non-negative")
if n_terms == 0:
return 1

squares = 4 * np.arange(1, n_terms+1) ** 2
prod = np.prod(squares / (squares - 1))

return prod * 2
68 changes: 53 additions & 15 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,33 +25,50 @@
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."""

def __init__(self): # noqa: D107
pass

def fit(self, X, y):
"""Write docstring.

And describe parameters
"""Fit the one-nearest-neighbor classifier.

Parameters
----------
X : ndarray of shape (n_samples, n_features)
The training samples.
y : ndarray of shape (n_samples, )
The training labels.

Returns
-------
self : OneNearestNeighbor
The fitted estimator.
"""
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_train_ = X
self.y_train_ = y
return self

def predict(self, X):
"""Write docstring.
"""Predict the class of each sample of X.

Parameters
----------
X : ndarray of shape (n_samples, n_features)
The samples to classify.

And describe parameters
Returns
-------
y_pred : ndarray of shape (p_samples, )
The predicted class of each sample of X.
"""
check_is_fitted(self)
X = check_array(X)
Expand All @@ -60,16 +77,37 @@ def predict(self, X):
dtype=self.classes_.dtype
)

# XXX fix
if X.shape[1] != self.n_features_in_:
raise ValueError(
f"X has {X.shape[1]} features, but "
f"{self.__class__.__name__} is expecting "
f"{self.n_features_in_} features as input"
)

diff = X[:, np.newaxis, :] - self.X_train_[np.newaxis, :, :]
dist = np.linalg.norm(diff, axis=2)
nearest = dist.argmin(axis=1)
y_pred = self.y_train_[nearest]

return y_pred

def score(self, X, y):
"""Write docstring.

And describe parameters
"""Return the accuracy of the classifier on (X,y).

Parameters
----------
X : ndarray of shape (n_samples, n_features)
The test samples.
y : ndarray of shape (n_samples, )
The test labels.

Returns
-------
score : float
The fraction of samples accurately classified.
"""
X, y = check_X_y(X, y)
y_pred = self.predict(X)

# XXX fix
return y_pred.sum()
y_pred = y_pred == y
return y_pred.mean()
Loading