Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UP my solution #122

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
56 changes: 46 additions & 10 deletions sklearn_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ def fit(self, X, y):
self : instance of KNearestNeighbors
The current instance of the classifier
"""
X, y = check_X_y(X, y)
check_classification_targets(y)
self.n_features_in_ = X.shape[1]
self.classes_ = np.unique(y)
self.X_ = X
self.y_ = y
return self

def predict(self, X):
Expand All @@ -97,8 +103,20 @@ def predict(self, X):
y : ndarray, shape (n_test_samples,)
Predicted class labels for each test data sample.
"""
y_pred = np.zeros(X.shape[0])
return y_pred
check_is_fitted(self)
X = check_array(X)
n_test_samples = X.shape[0]

y_pred = np.zeros(n_test_samples)

distance = pairwise_distances(X, self.X_, metric="euclidean")
distance_sorted = np.argsort(distance)[:, : self.n_neighbors]
k_classes = self.y_[distance_sorted]
y_pred = [
max(set(k.tolist()), key=k.tolist().count) for k in k_classes
]

return np.array(y_pred)

def score(self, X, y):
"""Calculate the score of the prediction.
Expand All @@ -115,7 +133,11 @@ def score(self, X, y):
score : float
Accuracy of the model computed for the (X, y) pairs.
"""
return 0.
check_is_fitted(self, ["X_", "y_"])
X = check_array(X)
y_pred = self.predict(X)
score = np.mean(y_pred == y)
return score


class MonthlySplit(BaseCrossValidator):
Expand Down Expand Up @@ -155,7 +177,13 @@ def get_n_splits(self, X, y=None, groups=None):
n_splits : int
The number of splits.
"""
return 0
X = X.reset_index()

if not isinstance(X[self.time_col][0], pd.Timestamp):
raise ValueError("X[time_col] does not contain datetime")

n_splits = X[self.time_col].dt.to_period("M").nunique() - 1
return n_splits

def split(self, X, y, groups=None):
"""Generate indices to split data into training and test set.
Expand All @@ -178,11 +206,19 @@ def split(self, X, y, groups=None):
The testing set indices for that split.
"""

n_samples = X.shape[0]
n_splits = self.get_n_splits(X, y, groups)
X = X.reset_index()
date_col = X[self.time_col]
period = X.resample("M", on=self.time_col).count().sort_index().index
period_m_y = period.map(lambda x: (x.month, x.year))
for i in range(n_splits):
idx_train = range(n_samples)
idx_test = range(n_samples)
yield (
idx_train, idx_test
)
df_train = X[
(date_col.dt.month == period_m_y[i][0])
& (date_col.dt.year == period_m_y[i][1])
]
df_test = X[
(date_col.dt.month == period_m_y[i + 1][0])
& (date_col.dt.year == period_m_y[i + 1][1])
]

yield (df_train.index.to_numpy(), df_test.index.to_numpy())
Loading