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
28 changes: 21 additions & 7 deletions numpy_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,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 must be a numpy array")

# TODO
if X.ndim != 2:
raise ValueError("Input must be 2D")

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

return int(i), int(j)


def wallis_product(n_terms):
Expand All @@ -62,6 +66,16 @@ 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

product = 1.0

for n in range(1, n_terms + 1):
numerator = (2 * n) ** 2
denominator = (2 * n - 1) * (2 * n + 1)
product *= numerator / denominator

pi = 2 * product

return pi
72 changes: 51 additions & 21 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,47 +28,77 @@
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

def fit(self, X, y):
"""Write docstring.

And describe parameters
"""Train the model by storing training data.

Parameters
----------
X : array-like, shape (n_samples, n_features)
Training samples.
y : array-like, shape (n_samples,)
Target values.

Returns
-------
self : object
Returns self.
"""
X, y = check_X_y(X, y)
check_classification_targets(y)
self.classes_ = np.unique(y)
self.n_features_in_ = X.shape[1]

# XXX fix
self.X_ = X
self.y_ = y
return self

def predict(self, X):
"""Write docstring.
"""Perform classification on test samples.

Parameters
----------
X : array-like, shape (n_samples, n_features)
Test samples.

And describe parameters
Returns
-------
y_pred : array, shape (n_samples,)
Class labels for samples in 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
)

# XXX fix
if X.shape[1] != self.n_features_in_:
raise ValueError(
f"X has {X.shape[1]} features, but OneNearestNeighbor "
f"is expecting {self.n_features_in_} features as input"
)
y_pred = np.zeros(len(X), dtype=self.y_.dtype)
for i in range(len(X)):
distances = np.sqrt(np.sum((self.X_ - X[i]) ** 2, axis=1))
nearest_idx = np.argmin(distances)
y_pred[i] = self.y_[nearest_idx]
return y_pred

def score(self, X, y):
"""Write docstring.

And describe parameters
"""Calculate mean accuracy.

Parameters
----------
X : array-like, shape (n_samples, n_features)
Test samples.
y : array-like, shape (n_samples,)
True labels.

Returns
-------
score : float
Mean accuracy.
"""
X, y = check_X_y(X, y)
y_pred = self.predict(X)

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