machine-learning - 将 GridSearchCV 与 TimeSeriesSplit 结合使用

标签 machine-learning scikit-learn regression grid-search

我有一些代码可以使用 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')

原始代码如下:

# Create the time series split generator
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]

# scale the data set
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)


# optimization area - set params
parameters = [
    {'kernel': ['rbf'],
     'gamma': [.01],
     'C': [ 1,10,100,500,1000]}]


regressor = SVR()
# loop through each of the parameters and find the best set
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


# refit the model with the best set of params

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 参数来查看运行输出。

关于machine-learning - 将 GridSearchCV 与 TimeSeriesSplit 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56546881/

相关文章:

python-3.x - 使用具有对数损失和 RFECV 的不平衡数据集的问题

python - 为什么我的非常简单的神经网络表现不佳?

scikit-learn - 如何在sklearn中对连续属性进行离散化?

excel - 如何根据 Excel 中的相关性/回归来恢复(预测)数据?

r - plm 函数和异方差鲁棒标准误差

python - Tensorflow 图像对象位置

machine-learning - 如何使用resnet50模型进行微调?

python - 如何在 iris 数据集上使用逻辑回归修复值错误

python - scikit-learn - 以概率为目标变量的多项逻辑回归

r - 使用 R 中的 "diversity"函数的 blau 索引的下标错误