简体   繁体   English

如何在Sklearn中重新拟合最佳分类器

[英]How to re-fit best classifier in sklearn

Using scikit-learn, I fit a classifier using Grid Search like this: 使用scikit-learn,我可以使用Grid Search来适合分类器,如下所示:

from sklearn.svm import SVC
param_grid = { 
    'C': [1e-2, 0.1, 1.0],
    'gamma': [1e-4, 1e-3, 1e-2],
    'class_weight': ['auto']
}

clf = SVC()
gs = grid_search.GridSearchCV(clf, param_grid, cv=3, n_jobs=12)
gs.fit(x_train, y_train)

I now want to re-train the classifier using the best parameters found and the extra argument probability=True . 现在,我想使用找到的最佳参数和额外的论点probability=True重新训练分类器。 How can I re-fit the classifier using the best parameters, plus the extra parameter probability ? 如何使用最佳参数加上额外的参数probability来重新拟合分类器?

您可以使用gs.best_params_获取参数,然后像这样创建一个新的分类器

clf = SVC(probability=True, **gs.best_params_)

You can also use the set_params method for an instance of SVC and modify the probability attribute before calling fit . 您还可以将set_params方法用于SVC的实例,并在调用fit之前修改probability属性。

from sklearn import svm, grid_search

x_train = np.random.randn(10,5)
y_train = np.random.randint(0, 2, size=(10,1))

param_grid = { 
    'C': [1e-2, 0.1, 1.0],
    'gamma': [1e-4, 1e-3, 1e-2],
    'class_weight': ['auto']
}

svc1 = svm.SVC()
gs = grid_search.GridSearchCV(svc1, param_grid, cv=3, n_jobs=12)
gs_fitted = gs.fit(x_train, y_train)

svc2 = svm.SVC(probability=True)
# or manually set svc2.probability = True before ever calling svc2.fit

svc2.set_params(**gs_fitted.best_params_)
svc2.fit(x_train, y_train)

Try 尝试

best_estimator = grid_search.best_estimator_.set_params(probability=True)

You can also clone it to be sure no other part of your code reuses this estimator. 您也可以克隆它,以确保代码的其他部分都不会重用此估计器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM