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
31 changes: 22 additions & 9 deletions numpy_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,20 @@ def max_index(X):
If the input is not a numpy array or
if the shape is not 2D.
"""
i = 0
j = 0

# TODO

return i, j
if not isinstance(X, np.ndarray):
raise ValueError("Input must be a numpy array.")
if X.ndim != 2:
raise ValueError("Input array must be 2D.")
i_max = 0
j_max = 0
max_value = X[0, 0]
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 +70,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 n in range(1, n_terms + 1):
numerator = 4 * n * n
denominator = numerator - 1
product *= numerator / denominator
return product * 2.0
61 changes: 45 additions & 16 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 @@ -28,47 +29,75 @@
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
"""Fit the OneNearestNeighbor model.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
The training input samples.
y : ndarray of shape (n_samples,)
The 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
"""Predict the class labels for the given samples.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Input samples.
Returns
-------
y_pred : ndarray of shape (n_samples,)
Predicted class labels for each sample.
"""
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.
"""Compute the mean accuracy on the given test data and labels.

And describe parameters
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Test samples.

y : ndarray of shape (n_samples,)
True labels for X.

Returns
-------
score : float
Mean accuracy of the classifier on the test data.
"""
X, y = check_X_y(X, y)
a = 1
y_pred = self.predict(X)

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