Skip to content
Open
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: 15 additions & 3 deletions numpy_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,13 @@ def max_index(X):
i = 0
j = 0

# TODO

if not isinstance(X, np.ndarray) or X.ndim != 2:
raise ValueError("X must be a 2D numpy array")
else:
for n in range(X.shape[0]):
for m in range(X.shape[1]):
if X[n, m] > X[i, j]:
i, j = n, m
return i, j


Expand All @@ -64,4 +69,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:
wallis = 1
else:
wallis = 1
for n in range(n_terms):
wallis *= (4 * (n+1)**2)/((4 * (n+1)**2) - 1)
wallis *= 2
return wallis
26 changes: 21 additions & 5 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@


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

def __init__(self): # noqa: D107
pass
Expand All @@ -45,7 +45,8 @@ def fit(self, X, 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):
Expand All @@ -55,12 +56,27 @@ def predict(self, X):
"""
check_is_fitted(self)
X = check_array(X)
if X.shape[1] != self.n_features_in_:
raise ValueError(
f"X has {X.shape[1]} features, but {self.__class__.__name__} "
f"is expecting {self.n_features_in_} features as input."
)
y_pred = np.full(
shape=len(X), fill_value=self.classes_[0],
dtype=self.classes_.dtype
)

# XXX fix
for i in range(len(X)):
min_dist = None
index_min = None
x = X[i]
for j in range(len(self.X_train_)):
x_train = self.X_train_[j]
dist = np.linalg.norm(x - x_train)
if min_dist is None or dist < min_dist:
min_dist = dist
index_min = j
y_pred[i] = self.y_train_[index_min]
return y_pred

def score(self, X, y):
Expand All @@ -70,6 +86,6 @@ def score(self, X, y):
"""
X, y = check_X_y(X, y)
y_pred = self.predict(X)
accuracy = sum(y_pred == y) / len(y)

# XXX fix
return y_pred.sum()
return accuracy
Loading