通过使用相同参数运行单个模型无法重现GridSearchCV / RandomizedSearchCV的结果

时间:2019-07-02 13:05:20

标签: machine-learning scikit-learn cross-validation grid-search

我正在运行5倍的RandomizedSearchCV,以便找到最佳参数。我有一个预测套用(X_test)。我的部分代码是:

svc= SVC(class_weight=class_weights, random_state=42)
Cs = [0.01, 0.1, 1, 10, 100, 1000, 10000]
gammas = [1e-1, 1e-2, 1e-3, 1e-4, 1e-5]

param_grid = {'C': Cs,
              'gamma': gammas,
              'kernel': ['linear', 'rbf', 'poly']}

my_cv = TimeSeriesSplit(n_splits=5).split(X_train)
rs_svm = RandomizedSearchCV(SVC(), param_grid, cv = my_cv, scoring='accuracy', 
                              refit='accuracy', verbose = 3, n_jobs=1, random_state=42)
rs_svm.fit(X_train, y_train)
y_pred = rs_svm.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
clfreport = classification_report(y_test, y_pred)
print (rs_svm.best_params_)

结果是分类报告: encodeURIComponent

现在,我有兴趣使用具有所选参数的独立模型(无randomizedsearchCV)来重现此结果:

from sklearn.model_selection import TimeSeriesSplit
tcsv=TimeSeriesSplit(n_splits=5)
for train_index, test_index in tcsv.split(X_train):
    train_index_ = int(train_index.shape[0])
    test_index_ = int(test_index.shape[0])
    X_train_, y_train_ = X_train[0:train_index_],y_train[0:train_index_]
    X_test_, y_test_ = X_train[test_index_:],y_train[test_index_:]
    class_weights = compute_class_weight('balanced', np.unique(y_train_), y_train_)
    class_weights = dict(enumerate(class_weights))
    svc= SVC(C=0.01, gamma=0.1, kernel='linear', class_weight=class_weights, verbose=True,
             random_state=42)
    svc.fit(X_train_, y_train_)

y_pred_=svc.predict(X_test)
cm = confusion_matrix(y_test, y_pred_)
clfreport = classification_report(y_test, y_pred_)

据我了解,clfreports应该相同,但运行后的结果是:

Results after RS

有人对为什么会发生有任何建议吗?

1 个答案:

答案 0 :(得分:1)

给出您的第一个代码段,在其中您可以使用RandomizedSearchCV查找最佳的超参数,而无需再次进行任何拆分;因此,在第二个代码段中,应该只使用发现的超参数和整个训练集的班级权重来拟合,然后根据测试集进行预测:

class_weights = compute_class_weight('balanced', np.unique(y_train), y_train)
class_weights = dict(enumerate(class_weights))
svc= SVC(C=0.01, gamma=0.1, kernel='linear', class_weight=class_weights, verbose=True, random_state=42)
svc.fit(X_train, y_train)

y_pred_=svc.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
clfreport = classification_report(y_test, y_pred)

Order between using validation, training and test sets中的讨论可能有助于阐明过程...