时间序列——GridSearchCV&TimeSeriesSplit的调参(xgboost预测sin(x))

12 篇文章 100 订阅 ¥29.90 ¥99.00

1、 原始时间序列

data = np.sin(np.arange(0, 1000) * 0.05) * 10 + np.random.randn(1000)

在这里插入图片描述
2、GridSearchCV&TimeSeriesSplit的调参

# -*- coding: utf-8 -*- 
# @Time : 2021/12/21 13:42 
# @Author : Orange
# @File : test.py.py
from xgboost import XGBRegressor
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
import numpy as np
import matplotlib.pyplot as plt


# 以xgboost为例,给出时间序列的GridSearchCV结合TimeSeriesSplit的调参

def train(x_train, y_train):
    my_cv = TimeSeriesSplit(n_splits=4).split(x_train)
    cv_params = {'n_estimators': [6, 7, 8, 10, 20], 'learning_rate': [0.01, 0.1, 0.3, 1], 'max_depth': [4, 5, 6, 7, 8],
                 'min_child_weight': [4, 5, 6, 7, 8], 'gamma': [1, 3], 'reg_alpha': [0.1, 0.3]}
    other_params = {'learning_rate': 0.1, 'n_estimators': 90, 'max_depth': 7, 'min_child_weight': 4, 'seed': 0,
                    'subsample': 1, 'colsample_bytree': 0.9, 'gamma': 1, 'reg_alpha': 0.1, "lambda": 0.9}
    model = XGBRegressor(**other_params)
    optimized_GBM = GridSearchCV(estimator=model, param_grid=cv_params, scoring='neg_mean_absolute_error', cv=my_cv)
    optimized_GBM.fit(np.array(x_train), np.array(y_train))
    model = optimized_GBM.best_estimator_
    print('参数的最佳取值:{0}'.format(optimized_GBM.best_params_))
    print('最佳模型得分:{0}'.format(optimized_GBM.best_score_))
    return model


if __name__ == '__main__':
    data = np.sin(np.arange(0, 1000) * 0.05) * 10 + np.random.randn(1000)

    # 取当前时间为第500个数据所在的时刻
    # 特征取前500个数据,利用前500个数据预测后500个数据
    X = data[:500].reshape(500, 1)
    Y = data[500:]

    X_train = X[:400]
    Y_train = Y[:400]
    X_test = X[400:]
    Y_test = Y[400:]

    model = train(X_train, Y_train)
    Y_hat = model.predict(X_test)
    plt.figure()
    plt.plot(Y_test)
    plt.plot(Y_hat)
    plt.legend(['Y_test', 'Y_hat'])
    plt.show()

输出:参数的最佳取值:{‘gamma’: 1, ‘learning_rate’: 0.3, ‘max_depth’: 5, ‘min_child_weight’: 4, ‘n_estimators’: 20, ‘reg_alpha’: 0.3}

在这里插入图片描述

  • 4
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hellobigorange

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值