You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ktrain的TextPredictor绘制PR曲线提示需为二分类器,如何解决?

报错原因

sklearn的plot_precision_recall_curve函数要求传入的估算器必须符合sklearn分类器的接口规范,ktrain自带的TextPredictor没有实现对应接口,因此会被函数误判为非二分类器,并非你的模型本身不支持二分类任务。

解决方案

方案一:手动计算绘制PR曲线(推荐,更简单)

不需要改造Predictor,直接调用sklearn的底层计算接口自行绘图即可:

from sklearn.metrics import precision_recall_curve, average_precision_score
import matplotlib.pyplot as plt

# 1. 获取真实标签和正类预测概率
# *注意:此处需要传入测试集的真实标签,不要传入预测类别
y_true = df_testing.真实标签列.values
y_score = predictor.predict_proba(df_testing.description.values)[:, 1]

# 2. 计算PR曲线坐标和平均精度
precision, recall, _ = precision_recall_curve(y_true, y_score)
average_precision = average_precision_score(y_true, y_score)

# 3. 绘制曲线
plt.figure(figsize=(8, 6))
plt.plot(recall, precision, label=f'AP={average_precision:0.2f}')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('2-class Precision-Recall Curve')
plt.legend()
plt.show()

方案二:封装Predictor适配sklearn接口

如果需要直接使用plot_precision_recall_curve函数,可以写一个简单的包装类适配sklearn规范:

from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.metrics import plot_precision_recall_curve
import matplotlib.pyplot as plt

# 定义包装类
class KtrainBinaryClf(BaseEstimator, ClassifierMixin):
    def __init__(self, predictor):
        self.predictor = predictor
        # 按你的实际二分类类别填写,通常为[0,1]
        self.classes_ = [0, 1]
    
    def fit(self, X, y=None):
        # 模型已提前训练完成,无需实现
        return self
    
    def predict_proba(self, X):
        return self.predictor.predict_proba(X)

# 包装你的预测器
wrapped_clf = KtrainBinaryClf(predictor)

# 调用绘图函数,*注意第三个参数为真实标签,不是预测类别
disp = plot_precision_recall_curve(wrapped_clf, df_testing.description.values, df_testing.真实标签列.values)
disp.ax_.set_title(f'2-class Precision-Recall curve: AP={disp.average_precision:0.2f}')
plt.show()

注意事项

  • 你原代码中传入plot_precision_recall_curve的第三个参数是df_testing.pred_class,大概率是预测得到的类别,这是错误的,必须传入测试集的真实标签才能得到正确的PR曲线
  • 需确认你的ktrain模型是按二分类任务训练的,predict_proba返回结果的shape为(样本数量, 2)

内容的提问来源于stack exchange,提问作者nikviz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:48:01