1. 程式人生 > >【機器學習】時序資料處理

【機器學習】時序資料處理

相關參考文獻:

1.時間序列交叉驗證

2.機器學習與時間序列預測

3.時序資料預測案例: O2O Coupon Usage Forecast

4.時間序列模型中樣本時間視窗的選擇-華泰期貨

5.scikit-learn交叉驗證時間序列資料的自定義拆分

6.Feature Selection for Time Series Forecasting with Python

 

一、背景

最近在做專案的時候,出現這樣的情況:模型在隨機劃分的測試集上表現很,卻在按月劃分的測試集上表現極其

分析發現樣本集具有時序性,在模型訓練時未將時間因素考慮在內,導致模型泛化能力差;基於此,調整模型調參時的交叉驗證方式,由系統隨機劃分改為自定義按月劃分

 

二、自定義交叉驗證資料集

具體Python程式碼如下:

1.自定義交叉驗證劃分規則:

# 自定義交叉驗證(月)
def data2lst(lst):
    ret = []
    for i in lst:
        ret += i
    return ret

def createCv(x_train_month, x_train, y_train, n):
    groups = x_train.groupby(x_train_month).groups
    sorted_groups = [value.tolist() for (key, value) in sorted(groups.items())]
    cv = [(np.array(data2lst(sorted_groups[i:i+n])), np.array(sorted_groups[i+n])) for i in range(len(sorted_groups)-n)]
    return cv

2.測試

# 隨機生成測試資料
import pandas as pd
import numpy as np
x_train = pd.DataFrame(list(range(100)), columns=['col0'])
y_train = pd.DataFrame([np.random.randint(0, 2) for i in range(100)], columns=['y'])
x_train_month = ['2018-01']*20 + ['2018-02']*20 + ['2018-03']*20 + ['2018-04']*20 + ['2018-05']*20

# 3個月訓練,1個月驗證    
n = 3
cv = createCv(x_train_month, x_train, y_train, n)  # 返回x_train的index
print(len(cv))
print(cv)

# 搭配GridSearchCV使用
param_test = {'max_depth': list(range(5,12,2))}
gsearch1 = GridSearchCV(
        estimator=XGBClassifier()
        , param_grid = param_test
        , cv=cv)

三、結果

1.能有效解決過擬合現象;

2.在測試集上的效果稍有提升;

3.某種程度上提升模型訓練效率