在Python中绘制P-R(Precision-Recall)曲线,你需要安装`matplotlib`、`numpy`和`sklearn`这三个第三方库。以下是绘制P-R曲线的步骤和代码示例:
步骤
1. 导入必要的库:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve
2. 准备数据:
```python
y_true 是样本的真实标签,1 表示正例,0 表示负例
y_true = np.array([1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0])
probas_pred 是模型预测为正例的概率
probas_pred = np.array([0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.95, 0.9, 0.85, 0.8, 0.75, 0.7, 0.65, 0.6, 0.55, 0.5, 0.45, 0.4])
3. 计算P-R曲线:
```python
precision, recall, thresholds = precision_recall_curve(y_true, probas_pred)
4. 绘制P-R曲线:
```python
plt.figure("Precision/Recall Curve")
plt.title("Precision/Recall Curve")
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.plot(recall, precision, marker='.')
plt.show()
代码示例
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve
准备数据
y_true = np.array([1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0])
probas_pred = np.array([0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.95, 0.9, 0.85, 0.8, 0.75, 0.7, 0.65, 0.6, 0.55, 0.5, 0.45, 0.4])
计算P-R曲线
precision, recall, thresholds = precision_recall_curve(y_true, probas_pred)
绘制P-R曲线
plt.figure("Precision/Recall Curve")
plt.title("Precision/Recall Curve")
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.plot(recall, precision, marker='.')
plt.show()
运行上述代码,你将得到一个展示P-R曲线的图形。
解释
`precision_recall_curve` 函数计算给定预测概率下的查准率(Precision)和查全率(Recall)。
`precision` 是查准率,即正确预测为正例的样本数除以所有预测为正例的样本数。
`recall` 是查全率,即正确预测为正例的样本数除以所有实际为正例的样本数。
`thresholds` 是用于划分查准率和查全率的阈值。
希望这能帮助你绘制P-R曲线