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
Binary file added .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions github-assignment
Submodule github-assignment added at 769c2d
19 changes: 15 additions & 4 deletions numpy_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,15 @@ def max_index(X):
If the input is not a numpy array or
if the shape is not 2D.
"""
if not isinstance(X, np.ndarray):
raise ValueError("X must be a numpy array.")
if X.ndim != 2:
raise ValueError("X must be a 2D array.")
i = 0
j = 0

# TODO
flat_index = np.argmax(X)
i, j = np.unravel_index(flat_index, X.shape)

return i, j

Expand All @@ -62,6 +67,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:
return 1.0
product = 1.0

for n in range(1, n_terms + 1):
product *= (4 * n**2) / (4 * n**2 - 1)

pi = 2 * product
return pi
81 changes: 63 additions & 18 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,46 +29,91 @@


class OneNearestNeighbor(BaseEstimator, ClassifierMixin):
"OneNearestNeighbor classifier."
"""One Nearest Neighbor classifier.

def __init__(self): # noqa: D107
This classifier predicts the label of the closest training sample
using the Euclidean distance.
"""

def __init__(self):
"""Initialize the OneNearestNeighbor classifier."""
pass

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

Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data.

y : array-like of shape (n_samples,)
Class labels.

And describe parameters
Returns
-------
self : object
The fitted classifier.
"""
X, y = check_X_y(X, y)
check_classification_targets(y)

self.X_ = X
self.y_ = y
self.classes_ = np.unique(y)
self.n_features_in_ = X.shape[1]

# XXX fix
return self

def predict(self, X):
"""Write docstring.
"""Predict the closest label for each sample.

Parameters
----------
X : array-like of shape (n_samples, n_features)
Input samples.

And describe parameters
Returns
-------
y_pred : ndarray of shape (n_samples,)
Predicted class labels.
"""
check_is_fitted(self)
check_is_fitted(self, ["X_", "y_", "n_features_in_"])
X = check_array(X)
y_pred = np.full(
shape=len(X), fill_value=self.classes_[0],
dtype=self.classes_.dtype
)

# XXX fix
if X.shape[1] != self.n_features_in_:
raise ValueError(
"X has {} features, but OneNearestNeighbor was fitted with "
"{} features.".format(X.shape[1], self.n_features_in_)
)

n_samples = X.shape[0]
y_pred = np.empty(n_samples, dtype=self.y_.dtype)

for i in range(n_samples):
# Compute Euclidean distances to all training samples
distances = np.linalg.norm(self.X_ - X[i], axis=1)
nn_index = np.argmin(distances)
y_pred[i] = self.y_[nn_index]

return y_pred

def score(self, X, y):
"""Write docstring.
"""Return accuracy of the classifier.

Parameters
----------
X : array-like of shape (n_samples, n_features)
Test samples.

And describe parameters
y : array-like of shape (n_samples,)
True labels.

Returns
-------
score : float
Accuracy (fraction of correct predictions).
"""
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