|
63 | 63 | # and then we evaluate other cross-validation methods. |
64 | 64 |
|
65 | 65 | # %% |
66 | | -from sklearn.model_selection import train_test_split |
67 | | - |
68 | 66 | 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) |
78 | 67 |
|
79 | 68 | # %% [markdown] |
80 | 69 | # We will use a decision tree regressor that we expect to overfit and thus not |
|
102 | 91 | # %% |
103 | 92 | from sklearn.model_selection import cross_val_score |
104 | 93 |
|
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) |
108 | 95 | print(f"The mean R2 is: {test_score.mean():.2f} ± {test_score.std():.2f}") |
109 | 96 |
|
110 | 97 | # %% [markdown] |
|
118 | 105 | # `train_test_split` for this purpose. |
119 | 106 |
|
120 | 107 | # %% |
| 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 | + |
121 | 120 | regressor.fit(data_train, target_train) |
122 | 121 | 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 |
124 | 123 | target_predicted = pd.Series(target_predicted, index=target_test.index) |
125 | 124 |
|
126 | 125 | # %% [markdown] |
|
165 | 164 | data, |
166 | 165 | target, |
167 | 166 | shuffle=False, |
168 | | - random_state=0, |
169 | 167 | ) |
170 | 168 | regressor.fit(data_train, target_train) |
171 | 169 | target_predicted = regressor.predict(data_test) |
|
0 commit comments