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
17 changes: 16 additions & 1 deletion numpy_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ def max_index(X):
j = 0

# TODO
if not isinstance(X, np.ndarray):
raise ValueError('Input must be a numpy array')
if X.ndim != 2:
raise ValueError('Input array must be 2D')

res = np.unravel_index(np.argmax(X), X.shape)
i, j = int(res[0]), int(res[1])

return i, j

Expand All @@ -64,4 +71,12 @@ 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

arr = np.arange(n_terms) + 1
arr = (4*arr**2)/(4*arr**2 - 1)
pi = arr.prod()*2

return pi
85 changes: 75 additions & 10 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,28 +30,77 @@


class OneNearestNeighbor(ClassifierMixin, BaseEstimator):
"OneNearestNeighbor classifier."
"""OneNearestNeighbor classifier.

Predict for each sample the target of the closest training sample,
using the Euclidean distance.

Attributes
----------
classes_ : ndarray of shape (n_classes,)
The unique class labels seen during `fit`.
n_features_in_ : int
The number of features seen during `fit`.
X_ : ndarray of shape (n_samples, n_features)
The training samples stored during `fit`.
y_ : ndarray of shape (n_samples,)
The training targets stored during `fit`.
"""

def __init__(self): # noqa: D107
pass

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

And describe parameters
"""Fit the OneNearestNeighbor classifier.

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.

Raises
------
ValueError
If `X` and `y` have inconsistent lengths, or if `y` is not a
valid classification target.
"""
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.
"""Predict the class labels for the provided samples.

Each sample is assigned the target of its nearest training sample
in Euclidean distance.

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

And describe parameters
Returns
-------
y_pred : ndarray of shape (n_queries,)
The predicted class label for each sample.

Raises
------
NotFittedError
If the classifier has not been fitted yet.
"""
check_is_fitted(self)
X = check_array(X)
Expand All @@ -61,15 +110,31 @@ def predict(self, X):
)

# XXX fix
X = validate_data(self, X, reset=False)
dist = X[:, None, :] - self.X_[None, :, :]
norm = np.linalg.norm(dist, axis=-1)
idx = np.argsort(norm, axis=-1)[:, 0]
y_pred = self.y_[idx]

return y_pred

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

And describe parameters
"""Return the accuracy on the given test data and labels.

Parameters
----------
X : ndarray of shape (n_queries, n_features)
The test samples.
y : ndarray of shape (n_queries,)
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)
Loading