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
21 changes: 17 additions & 4 deletions numpy_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -37,12 +38,16 @@ def max_index(X):
If the input is not a numpy array or
if the shape is not 2D.
"""
i = 0
j = 0
if not isinstance(X, np.ndarray):
raise ValueError("Input should be numpy array.")
if X.ndim != 2:
raise ValueError("Input should be 2D array.")

# TODO
max_val = X.max()
i, j = np.where(X == max_val)

return i, j
return i[0], j[0]


def wallis_product(n_terms):
Expand All @@ -64,4 +69,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.
pi_approx = 1

if n_terms == 0:
return pi_approx

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

return 2 * pi_approx
18 changes: 10 additions & 8 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@


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

def __init__(self): # noqa: D107
pass
Expand All @@ -41,10 +41,11 @@ def fit(self, X, y):
"""
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):
Expand All @@ -54,12 +55,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

# euclidean distances between X and self.X_
distances = np.linalg.norm(
self.X_[np.newaxis, :, :] - X[:, np.newaxis, :], axis=2
)
nearest_indices = np.argmin(distances, axis=1)
y_pred = self.y_[nearest_indices]

# XXX fix
return y_pred

def score(self, X, y):
Expand All @@ -70,5 +73,4 @@ def score(self, X, y):
X, y = check_X_y(X, y)
y_pred = self.predict(X)

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