我有一些代码可以使用 TimeSeriesSplit
来分割我的数据。对于每个拆分,我将使用 ParametersGrid
并循环遍历每个参数组合,记录最佳参数集并使用它来预测我的 X_test
。您可以在帖子底部看到这部分的代码
我知道 GridSearchCV
将为我做很多这样的工作。我想知道如果我使用以下代码,我的数据会在哪里分割成
X_train
、X_test
、y_train
和 y_test
?将 GridSearchCV
与 TimeSeriesSplit
一起使用会在幕后处理这个问题吗?如果是的话,这段代码会完成与本文底部的原始代码相同的任务吗?另外,我现在已经尝试了 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/