如何在Python中创建一个精确-召回曲线

613 阅读2分钟

在机器学习中使用分类模型时,我们经常使用两个指标来评估模型的质量,即精度和召回率。

精度。正确的正面预测相对于总的正面预测。

其计算方法为。

  • 精确率=真阳性/(真阳性+假阳性)。

召回率。正确的阳性预测相对于总的实际阳性预测而言。

其计算方法为。

  • 召回率=真阳性/(真阳性+假阴性)

为了可视化某个模型的精确性和召回率,我们可以创建一条精确-召回曲线 。这条曲线显示了不同阈值下精度和召回率之间的权衡。

Precision-recall curve in Python

下面的例子说明了如何在Python中为一个逻辑回归模型创建精度-召回率曲线。

第一步:导入软件包

首先,我们将导入必要的包。

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve
import matplotlib.pyplot as plt

第二步:拟合Logistic回归模型

接下来,我们将创建一个数据集,并对其进行Logistic回归模型拟合:

#create dataset with 5 predictor variables
X, y = datasets.make_classification(n_samples=1000,
                                    n_features=4,
                                    n_informative=3,
                                    n_redundant=1,
                                    random_state=0)

#split dataset into training and testing set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3,random_state=0)

#fit logistic regression model to dataset
classifier = LogisticRegression()
classifier.fit(X_train, y_train)

#use logistic regression model to make predictions
y_score = classifier.predict_proba(X_test)[:, 1]

第3步:创建准确率-召回率曲线

接下来,我们将计算模型的精确度和召回率,并创建一个精确度-召回率曲线:

#calculate precision and recall
precision, recall, thresholds = precision_recall_curve(y_test, y_score)

#create precision recall curve
fig, ax = plt.subplots()
ax.plot(recall, precision, color='purple')

#add axis labels to plot
ax.set_title('Precision-Recall Curve')
ax.set_ylabel('Precision')
ax.set_xlabel('Recall')

#display plot
plt.show()

Precision-recall curve in Python

X轴显示召回率,Y轴显示不同阈值的精度。

请注意,随着召回率的增加,精度会下降。

这代表了这两个指标之间的权衡。为了提高我们模型的召回率,精度必须降低,反之亦然。

其他资源

如何在Python中进行Logistic回归
如何在Python中创建混淆矩阵
如何解释ROC曲线(有例子)