Skip to content

Commit 721cbe1

Browse files
MTN Switched the use of cross validation and train_test_split in non iid data notebook (#834)
1 parent 13860a8 commit 721cbe1

1 file changed

Lines changed: 14 additions & 16 deletions

File tree

python_scripts/cross_validation_time.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -63,18 +63,7 @@
6363
# and then we evaluate other cross-validation methods.
6464

6565
# %%
66-
from sklearn.model_selection import train_test_split
67-
6866
data, target = quotes.drop(columns=["Chevron"]), quotes["Chevron"]
69-
data_train, data_test, target_train, target_test = train_test_split(
70-
data, target, shuffle=True, random_state=0
71-
)
72-
73-
# Shuffling breaks the index order, but we still want it to be time-ordered
74-
data_train.sort_index(ascending=True, inplace=True)
75-
data_test.sort_index(ascending=True, inplace=True)
76-
target_train.sort_index(ascending=True, inplace=True)
77-
target_test.sort_index(ascending=True, inplace=True)
7867

7968
# %% [markdown]
8069
# We will use a decision tree regressor that we expect to overfit and thus not
@@ -102,9 +91,7 @@
10291
# %%
10392
from sklearn.model_selection import cross_val_score
10493

105-
test_score = cross_val_score(
106-
regressor, data_train, target_train, cv=cv, n_jobs=2
107-
)
94+
test_score = cross_val_score(regressor, data, target, cv=cv, n_jobs=2)
10895
print(f"The mean R2 is: {test_score.mean():.2f} ± {test_score.std():.2f}")
10996

11097
# %% [markdown]
@@ -118,9 +105,21 @@
118105
# `train_test_split` for this purpose.
119106

120107
# %%
108+
from sklearn.model_selection import train_test_split
109+
110+
data_train, data_test, target_train, target_test = train_test_split(
111+
data, target, shuffle=True, random_state=0
112+
)
113+
114+
# Shuffling breaks the index order, but we still want it to be time-ordered
115+
data_train.sort_index(ascending=True, inplace=True)
116+
data_test.sort_index(ascending=True, inplace=True)
117+
target_train.sort_index(ascending=True, inplace=True)
118+
target_test.sort_index(ascending=True, inplace=True)
119+
121120
regressor.fit(data_train, target_train)
122121
target_predicted = regressor.predict(data_test)
123-
# Affect the index of `target_predicted` to ease the plotting
122+
# Recover the `DatetimeIndex` from `target_test` for correct plotting
124123
target_predicted = pd.Series(target_predicted, index=target_test.index)
125124

126125
# %% [markdown]
@@ -165,7 +164,6 @@
165164
data,
166165
target,
167166
shuffle=False,
168-
random_state=0,
169167
)
170168
regressor.fit(data_train, target_train)
171169
target_predicted = regressor.predict(data_test)

0 commit comments

Comments
 (0)