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

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

max_position = np.argmax(X)
return np.unravel_index(max_position, X.shape)

return i, j

Expand All @@ -62,6 +67,9 @@ 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

k = np.arange(1, n_terms + 1, dtype=float)
terms = (2 * k) ** 2 / ((2 * k - 1) * (2 * k + 1))
return 2.0 * np.prod(terms)
19 changes: 16 additions & 3 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,11 @@
from sklearn.utils.validation import check_X_y
from sklearn.utils.validation import check_array
from sklearn.utils.validation import check_is_fitted
from sklearn.utils.validation import validate_data
from sklearn.utils.multiclass import check_classification_targets


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

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

# XXX fix
return self
Expand All @@ -55,11 +56,23 @@ 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 OneNearestNeighbor is "
f"expecting {self.n_features_in_} features as input."
)

y_pred = np.full(
shape=len(X), fill_value=self.classes_[0],
dtype=self.classes_.dtype
)

for i, sample in enumerate(X):
distances = np.sum((self.X_train_ - sample) ** 2, axis=1)
nearest_index = np.argmin(distances)
y_pred[i] = self.y_train_[nearest_index]

# XXX fix
return y_pred

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

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