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
18 changes: 16 additions & 2 deletions numpy_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,15 @@ def max_index(X):
j = 0

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

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

return int(i), int(j)


def wallis_product(n_terms):
Expand All @@ -64,4 +71,11 @@ 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

n = np.arange(1, n_terms + 1, dtype=float)
terms = (2 * n / (2 * n - 1)) * (2 * n / (2 * n + 1))
product = np.prod(terms)

return 2.0 * product
18 changes: 11 additions & 7 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
from sklearn.utils.multiclass import check_classification_targets


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

def __init__(self): # noqa: D107
pass
Expand All @@ -41,6 +41,8 @@ def fit(self, X, y):
"""
X, y = check_X_y(X, y)
check_classification_targets(y)
self.X_train_ = X
self.y_train_ = y
self.classes_ = np.unique(y)
self.n_features_in_ = X.shape[1]

Expand All @@ -54,12 +56,14 @@ def predict(self, X):
"""
check_is_fitted(self)
X = check_array(X)
y_pred = np.full(
shape=len(X), fill_value=self.classes_[0],
dtype=self.classes_.dtype
)
self._check_n_features(X, reset=False)
y_pred = np.empty(X.shape[0], dtype=self.classes_.dtype)

# XXX fix
for i in range(len(X)):
distances = np.linalg.norm(self.X_train_ - X[i], axis=1)
nearest_index = np.argmin(distances)
y_pred[i] = self.y_train_[nearest_index]
return y_pred

def score(self, X, y):
Expand All @@ -71,4 +75,4 @@ def score(self, X, y):
y_pred = self.predict(X)

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