【问题标题】:Calibration prediction for multi-class classification多类分类的校准预测
【发布时间】:2020-03-10 19:39:00
【问题描述】:

我们如何进行多类分类的校准预测?

我尝试关注 https://machinelearningmastery.com/calibrated-classification-model-in-scikit-learn/ ,但这不适用于多类问题,因为当我使用 sklearn.calibration.calibration_curve 时出现以下错误:

ValueError:仅支持二进制分类。提供标签 ['x' 'y' 'z' 'a' 'b']。

【问题讨论】:

    标签: calibration


    【解决方案1】:

    一种方法是使用OneVsRestClassifier 重新训练您的多类模型,然后将每个类视为一个单独的模型。我在下面粘贴了一个我在 NLP 项目中使用的简单示例,希望对您有所帮助。

    # Binarize the output
    X_train = train_df['Text']
    X_test = test_df['Text']
    
    lb = LabelBinarizer()
    y_train = lb.fit_transform(train_df['Target'])
    y_test = lb.transform(test_df['Target'])
    
    # Train a model with tfidf-vectorizer and LinearSVC
    tfidf = TfidfVectorizer()
    clf = LinearSVC()
    clf = CalibratedClassifierCV(clf)
    clf = OneVsRestClassifier(clf)
    
    # Fit the model
    pipe = Pipeline([('tfidf', tfidf), ('clf', clf)])
    pipe.fit(X_train, y_train)
    
    # Plot the Calibration Curve for every class
    plt.figure(figsize=(20, 10))
    ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
    ax2 = plt.subplot2grid((3, 1), (2, 0))
    ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated")
    
    targets = range(len(lb.classes_))
    for target in targets:
        prob_pos = pipe.predict_proba(X_test)[:, target]
        fraction_of_positives, mean_predicted_value = calibration_curve(y_test[:, target], prob_pos, n_bins=10)
        name = lb.classes_[target]
    
        ax1.plot(mean_predicted_value, fraction_of_positives, "s-", label="%s" % (name, ))
        ax2.hist(prob_pos, range=(0, 1), bins=10, label=name, histtype="step", lw=2)
    
    ax1.set_ylabel("The proportion of samples whose class is the positive class")
    ax1.set_xlabel("The mean predicted probability in each bin")
    ax1.set_ylim([-0.05, 1.05])
    ax1.legend(loc="lower right")
    ax1.set_title('Calibration plots (reliability curve)')
    
    ax2.set_xlabel("Mean predicted value")
    ax2.set_ylabel("Count")
    ax2.legend(loc="upper center", ncol=2)
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

    • 变量lb从何而来? y_test 中的值是什么样的?
    • 我添加了一些以上示例中缺少的代码。我正在使用LabelBinarizer 对目标值进行二值化。请参阅链接了解 y_test 的外观。
    • 非常感谢!我让它为我的用例运行。
    【解决方案2】:

    sklearn.calibration.calibration_curve 会给您一个错误,因为校准曲线假定输入来自二元分类器(请参阅documentation)。

    但是,您要问的问题是是否可以对多类分类问题进行校准。根据scikit-learn documentation about calibration,这是可能的,它指出:

    CalibratedClassifierCV 还可以处理涉及两个以上类的分类任务,如果基础估计器可以这样做的话。在这种情况下,首先以一对一的方式分别为每个类校准分类器。在预测未见数据的概率时,分别预测每个类别的校准概率。由于这些概率不一定总和为 1,因此执行后处理以对其进行归一化。

    【讨论】:

    • 我们如何绘制具有多类的分类器?
    • 是的,对此有所了解会很棒
    猜你喜欢
    • 2020-05-23
    • 2019-08-20
    • 2022-01-20
    • 2020-03-20
    • 2020-08-06
    • 2021-08-17
    • 2019-04-19
    • 2018-10-12
    • 1970-01-01
    相关资源
    最近更新 更多