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
34 changes: 32 additions & 2 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 @@ -40,7 +41,21 @@ def max_index(X):
i = 0
j = 0

# TODO
if not isinstance(X, np.ndarray):
raise ValueError("Not a numpy array")

if X.ndim != 2:
raise ValueError("Not a 2D array")

n = X.shape[0]
m = X.shape[1]
max = 0
for k in range(n):
for p in range(m):
if X[k][p] > max:
max = X[k][p]
i = k
j = p

return i, j

Expand All @@ -64,4 +79,19 @@ 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.
product = 1.0

if n_terms == 0:
return 1.0

n = 1
while n <= n_terms:
numerator = 4 * n * n
denominator = (2 * n - 1) * (2 * n + 1)
product = product * (numerator / denominator)
n += 1

pi = product * 2

# approximation of order n_terms
return pi
24 changes: 15 additions & 9 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
for the methods you code and for the class. The docstring will be checked using
`pydocstyle` that you can also call at the root of the repo.
"""

import numpy as np
from sklearn.base import BaseEstimator
from sklearn.base import ClassifierMixin
Expand All @@ -29,7 +30,7 @@


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

def __init__(self): # noqa: D107
pass
Expand All @@ -44,7 +45,9 @@ 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 @@ -54,13 +57,16 @@ 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

distances = np.sqrt(
np.sum((
X[:, np.newaxis, :] - self.X_train_[np.newaxis, :, :]
) ** 2, axis=2
)
)
nearest_indices = np.argmin(distances, axis=1)

# XXX fix
return y_pred
return self.y_train_[nearest_indices]

def score(self, X, y):
"""Write docstring.
Expand All @@ -70,5 +76,5 @@ def score(self, X, y):
X, y = check_X_y(X, y)
y_pred = self.predict(X)

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