Machine Learning cho Dữ liệu Chuỗi thời gian bằng Python
Chris Holdgraf
Fellow, Berkeley Institute for Data Science
# Lặp qua phương thức "split" cho ra chỉ số train/test
for tr, tt in cv.split(X, y):
model.fit(X[tr], y[tr])
model.score(X[tt], y[tt])
KFold chia dữ liệu của bạn thành nhiều "fold" có kích thước bằng nhauĐây là một trong những quy trình xác thực chéo phổ biến nhất
from sklearn.model_selection import KFold
cv = KFold(n_splits=5)
for tr, tt in cv.split(X, y):
...
fig, axs = plt.subplots(2, 1)
# Vẽ các chỉ số được chọn cho tập kiểm định ở mỗi vòng lặp
axs[0].scatter(tt, [0] * len(tt), marker='_', s=2, lw=40)
axs[0].set(ylim=[-.1, .1], title='Chỉ số tập kiểm định (màu = vòng lặp CV)',
xlabel='Chỉ số dữ liệu gốc')
# Vẽ dự đoán của mô hình ở mỗi vòng lặp
axs[1].plot(model.predict(X[tt]))
axs[1].set(title='Dự đoán trên tập kiểm định ở mỗi vòng lặp CV',
xlabel='Chỉ số dự đoán')

Bạn không nên xáo trộn dữ liệu khi dự đoán với chuỗi thời gian.
from sklearn.model_selection import ShuffleSplit
cv = ShuffleSplit(n_splits=3)
for tr, tt in cv.split(X, y):
...

# Import và khởi tạo bộ lặp xác thực chéo
from sklearn.model_selection import TimeSeriesSplit
cv = TimeSeriesSplit(n_splits=10)
fig, ax = plt.subplots(figsize=(10, 5))
for ii, (tr, tt) in enumerate(cv.split(X, y)):
# Vẽ chỉ số train và test
l1 = ax.scatter(tr, [ii] * len(tr), c=[plt.cm.coolwarm(.1)],
marker='_', lw=6)
l2 = ax.scatter(tt, [ii] * len(tt), c=[plt.cm.coolwarm(.9)],
marker='_', lw=6)
ax.set(ylim=[10, -1], title='Hành vi TimeSeriesSplit',
xlabel='chỉ số dữ liệu', ylabel='vòng lặp CV')
ax.legend([l1, l2], ['Train', 'Validation'])

def myfunction(estimator, X, y):
y_pred = estimator.predict(X)
my_custom_score = my_custom_function(y_pred, y)
return my_custom_score
def my_pearsonr(est, X, y):
# Tạo dự đoán và chuyển thành vector
y_pred = est.predict(X).squeeze()
# Dùng hàm numpy "corrcoef" để tính ma trận tương quan
my_corrcoef_matrix = np.corrcoef(y_pred, y.squeeze())
# Trả về một giá trị tương quan từ ma trận
my_corrcoef = my_corrcoef[1, 0]
return my_corrcoef
Machine Learning cho Dữ liệu Chuỗi thời gian bằng Python