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
19 changes: 17 additions & 2 deletions numpy_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,12 @@ def max_index(X):
i = 0
j = 0

# TODO
if not isinstance(X, np.ndarray) or X.ndim != 2:
raise ValueError

max_index = np.argmax(X)
i = max_index // X.shape[1]
j = max_index % X.shape[1]

return i, j

Expand All @@ -64,4 +69,14 @@ 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
for i in range(1, n_terms+1):
numerator = 4*i*i
denominator = numerator - 1
product *= numerator/denominator

if n_terms == 0:
return product
else:
return product*2
61 changes: 49 additions & 12 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,28 +29,50 @@


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

def __init__(self): # noqa: D107
pass

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

Parameters
----------
X : ndarray of shape (n_samples, n_features)
The input array of samples.

y : ndarray of shape (n_samples,).
The input array of targets.

Returns
-------
self : OneNearestNeighbor
The fitted estimator.

And describe parameters
"""
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.
"""Predict the targets of training samples.

Parameters
----------
X : ndarray of shape (n_samples, n_features)
The input array of test samples.

Returns
-------
y_pred : ndarray of shape (n_samples,)
The output array of predictions.

And describe parameters
"""
check_is_fitted(self)
X = check_array(X)
Expand All @@ -59,16 +81,31 @@ def predict(self, X):
dtype=self.classes_.dtype
)

# XXX fix
for i, x in enumerate(X):
distances = np.linalg.norm(self._X_train - x, axis=1)
nearest_index = np.argmin(distances)
y_pred[i] = self._y_train[nearest_index]

return y_pred

def score(self, X, y):
"""Write docstring.
"""Compute accuracy score of predictions.

Parameters
----------
X : ndarray of shape (n_samples, n_features)
The input array of test samples.

y : ndarray of shape (n_samples,).
The input array of targets.

Returns
-------
accuracy : float
Fraction of correctly classified samples.

And describe parameters
"""
X, y = check_X_y(X, y)
y_pred = self.predict(X)

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