【机器学习】时序数据处理

相关参考文献:

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.某种程度上提升模型训练效率

猜你喜欢

转载自blog.csdn.net/qq_34105362/article/details/85257254