【问题标题】:GridSearchCV for the multi-class SVM in pythonpython中多类SVM的GridSearchCV
【发布时间】:2018-11-18 00:53:48
【问题描述】:

我正在尝试学习如何为分类器找到最佳参数。所以,我使用 GridSearchCV 来解决多类分类问题。在Does not GridSearchCV support multi-class? 上生成了一个虚拟代码,我只是将该代码与 n_classes=3 一起使用。

import numpy as np
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler,label_binarize
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import accuracy_score, recall_score, f1_score, roc_auc_score, make_scorer

X, y = make_classification(n_samples=3000, n_features=10, weights=[0.1, 0.9, 0.3],n_classes=3, n_clusters_per_class=1,n_informative=2)

pipe = make_pipeline(StandardScaler(), SVC(kernel='rbf', class_weight='auto'))

param_space = dict(svc__C=np.logspace(-5,0,5), svc__gamma=np.logspace(-2, 2, 10))

f1_score
my_scorer = make_scorer(f1_score, greater_is_better=True)

gscv = GridSearchCV(pipe, param_space, scoring=my_scorer)

我正在尝试按照此处Scikit-learn GridSearch giving "ValueError: multiclass format is not supported" error 的建议进行一次性编码。此外,有时会有像Toxic Comment Classification dataset on Kaggle 这样的数据集,它会给你二值化标签。

y = label_binarize(y, classes=[0, 1, 2])
for i in classes:    
gscv.fit(X, y[i])

print gscv.best_params_

我得到:

ValueError: bad input shape (2000L, 3L)

我不确定为什么会收到此错误。我的目标是为多类分类问题找到最佳参数。

【问题讨论】:

    标签: python scikit-learn svm grid-search


    【解决方案1】:

    你的代码的两部分有两个问题。

    1) 让我们从尚未对标签进行一次性编码的第一部分开始。你看,SVC 支持多类案例就好了。但是f1_score 与(内部)GridSearchCV 结合时不会。

    f1_score 默认情况下在二进制分类的情况下返回正标签的分数,因此在您的情况下会抛出错误。

    OR 它也可以返回一个分数数组(每个类一个),但是 GridSearchCV 只接受一个值作为分数,因为它需要它来找到最佳分数和超的最佳组合参数。所以需要通过f1_score中的求平均方法,从数组中获取单个值。

    根据f1_score documentation,允许以下平均方法:

    average : string, [None, ‘binary’ (默认), ‘micro’, ‘macro’, ‘样本’, ‘加权’]

    所以像这样改变你的 make_scorer:

    my_scorer = make_scorer(f1_score, greater_is_better=True, average='micro')
    

    根据您的需要更改上面的'average' 参数。

    2) 现在进入第二部分:当您对标签进行 one-hot 编码时,y 的形状变为二维,但 SVC 仅支持一维数组,如 y 中指定的文档:

    fit(X, y, sample_weight=None)[source]
    
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
        y : array-like, shape (n_samples,)
    

    但是,即使您对标签进行编码并使用支持二维标签的分类器,也必须解决第一个错误。因此,我建议您不要一次性对标签进行编码,而只需更改 f1_score

    【讨论】:

    • 谢谢,@Vivek Kumar 我可以手动选择 y(目标)来解决问题 #2。但是,然后我认为我需要在循环中拟合(X,y)和 GridSearch,我不确定是否可以这样做。这是主要问题。
    • for i in classes: gscv.fit(X, y[i]) 像这样。这样我就只有一维的标签了。
    猜你喜欢
    • 2016-05-11
    • 2016-07-15
    • 2020-10-29
    • 2015-07-17
    • 2015-10-15
    • 2013-05-20
    • 2021-10-12
    • 2019-07-06
    • 2021-05-23
    相关资源
    最近更新 更多