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
30 changes: 23 additions & 7 deletions numpy_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,23 @@ 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("X must be a numpy array")
if X.ndim != 2:
raise ValueError("X must be a 2D numpy array")

# TODO
i_max = 0
j_max = 0
max_value = X[0, 0]

return i, j
for i in range(X.shape[0]):
for j in range(X.shape[1]):
if X[i, j] >= max_value:
max_value = X[i, j]
i_max = i
j_max = j

return i_max, j_max


def wallis_product(n_terms):
Expand All @@ -62,6 +73,11 @@ 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
for i in range(1, n_terms + 1):
numerator = 4 * i * i
denominator = numerator - 1
product *= numerator / denominator
return 2.0 * product
54 changes: 45 additions & 9 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,47 +28,83 @@
from sklearn.utils.multiclass import check_classification_targets


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

A sample based on the class of its nearest neighbor in the training
set, using Euclidean distance.
"""

def __init__(self): # noqa: D107
pass

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

And describe parameters
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training samples.
y : array-like of shape (n_samples,)
Target values (class labels).
"""
X, y = check_X_y(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

def predict(self, X):
"""Write docstring.

And describe parameters
Parameters
----------
X : array-like of shape (n_samples, n_features)
Samples to predict.

Returns
-------
y_pred : ndarray of shape (n_samples,)
Predicted class labels.
"""
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 "
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)):
distances = np.sqrt(np.sum((self.X_train_ - X[i]) ** 2, axis=1))
nearest_idx = np.argmin(distances)
y_pred[i] = self.y_train_[nearest_idx]

return y_pred

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

And describe parameters
Parameters
----------
X : array of shape (n_samples, n_features)
Test samples.
y : array of shape (n_samples,)
True labels for X.

Returns
-------
score : float
Mean accuracy of self.predict(X) with respect to 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)