使用 GridSearchCV 与 TimeSeriesSplit

我有一些代码使用 TimeSeriesSplit 来分割我的数据。对于每次分割,我会使用 ParametersGrid 并遍历每个参数组合,记录最佳参数集并用它来预测我的 X_test。您可以在帖子的底部看到这部分的代码

我了解 GridSearchCV 可以为我完成很多工作。我想知道如果我使用以下代码,我的数将会如何被分割成 X_trainX_testy_trainy_test?使用 GridSearchCVTimeSeriesSplit 是否会在幕后处理这些,如果是的话,这段代码是否会实现与我在这篇文章底部的原始代码相同的功能?此外,我现在已经尝试了 GridSearchCV 方法,但它已经运行了将近30分钟还没有完成——我的语法是否正确?

X = data.iloc[:, 0:8]
y = data.iloc[:, 8:9]
parameters = [
    {'kernel': ['rbf'],
     'gamma': [.01],
     'C': [1, 10, 100]}]
gsc = GridSearchCV(SVR(), param_grid=parameters, scoring='neg_mean_absolute_error',
                    cv=TimeSeriesSplit(n_splits=2))
gsc.fit(X,y)
means = gsc.cv_results_['mean_test_score']
for mean in means:
    print(mean)
print('end')

原始代码如下:

# 创建时间序列分割生成器
tscv = TimeSeriesSplit(n_splits=3)
for train_index, test_index in tqdm(tscv.split(X)):
    X_train, X_test = X.iloc[train_index], X.iloc[test_index]
    y_train, y_test = y.iloc[train_index], y.iloc[test_index]
    # 缩放数据集
    scaler_X = StandardScaler()
    scaler_y = StandardScaler()
    scaler_X.fit(X_train)
    scaler_y.fit(y_train)
    X_train, X_test = scaler_X.transform(X_train), scaler_X.transform(X_test)
    y_train, y_test = scaler_y.transform(y_train), scaler_y.transform(y_test)
    # 优化区域 - 设置参数
    parameters = [
        {'kernel': ['rbf'],
         'gamma': [.01],
         'C': [ 1,10,100,500,1000]}]
    regressor = SVR()
    # 遍历每个参数并找出最佳参数集
    for e, g in enumerate(ParameterGrid(parameters)):
        regressor.set_params(**g)
        regressor.fit(X_train, y_train.ravel())
        score = metrics.mean_absolute_error(regressor.predict(X_train), y_train.ravel())
        if e == 0:
            best_score = score
            best_params = g
        elif score < best_score:
            best_score = score
            best_params = g
    # 使用最佳参数集重新拟合模型
    regressor.set_params(**best_params)
    regressor.fit(X_train, y_train.ravel())

回答:

您需要稍作修改代码。

gsc = GridSearchCV(SVR(), param_grid=parameters, scoring='neg_mean_absolute_error',
                    cv=TimeSeriesSplit(n_splits=2).split(X))

此外,您可以考虑添加 verbose 参数来查看运行输出。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注