我有一个在 X
上运行的估计器的结果,以及真实值,我想使用 plot_precision_recall_curve
,但这需要传入 estimator
和 X
– 而我无法做到这一点,估计器非常复杂,并且位于另一个系统中… 我该怎么办?(最好有一个版本的 plot_precision_recall_curve
,它接受 y_pred
和 y_true
…)。
回答:
你可以使用 precision_recall_curve,它接受 y_true
和 y_pred
,并返回 precision
、recall
和 thresholds
,这些可以进一步用于计算 f1_score 和 auc,后者可以让你手动绘制曲线。
这是一个示例:
# precision-recall curve and f1from sklearn.datasets import make_classificationfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import precision_recall_curvefrom sklearn.metrics import f1_scorefrom sklearn.metrics import aucfrom matplotlib import pyplot# generate 2 class datasetX, y = make_classification(n_samples=1000, n_classes=2, random_state=1)# split into train/test setstrainX, testX, trainy, testy = train_test_split(X, y, test_size=0.5, random_state=2)# fit a modelmodel = LogisticRegression(solver='lbfgs')model.fit(trainX, trainy)# predict probabilitieslr_probs = model.predict_proba(testX)# keep probabilities for the positive outcome onlylr_probs = lr_probs[:, 1]# predict class valuesyhat = model.predict(testX)lr_precision, lr_recall, _ = precision_recall_curve(testy, lr_probs)lr_f1, lr_auc = f1_score(testy, yhat), auc(lr_recall, lr_precision)# summarize scoresprint('Logistic: f1=%.3f auc=%.3f' % (lr_f1, lr_auc))# plot the precision-recall curvesno_skill = len(testy[testy==1]) / len(testy)pyplot.plot([0, 1], [no_skill, no_skill], linestyle='--', label='No Skill')pyplot.plot(lr_recall, lr_precision, marker='.', label='Logistic')# axis labelspyplot.xlabel('Recall')pyplot.ylabel('Precision')# show the legendpyplot.legend()# show the plotpyplot.show()