python实现 P-R曲线类,不用sklearn
时间: 2024-04-18 19:33:37 浏览: 79
利用鸢尾花数据集画出P-R曲线 python
你可以使用Python来实现P-R曲线类,以下是一个简单的示例代码:
```python
import matplotlib.pyplot as plt
class PRCurve:
def __init__(self, y_true, y_scores):
self.y_true = y_true
self.y_scores = y_scores
def precision_recall_curve(self):
thresholds = sorted(set(self.y_scores), reverse=True)
precisions = []
recalls = []
for threshold in thresholds:
y_pred = [1 if score >= threshold else 0 for score in self.y_scores]
true_positives = sum([1 for yt, yp in zip(self.y_true, y_pred) if yt == 1 and yp == 1])
false_positives = sum([1 for yt, yp in zip(self.y_true, y_pred) if yt == 0 and yp == 1])
false_negatives = sum([1 for yt, yp in zip(self.y_true, y_pred) if yt == 1 and yp == 0])
precision = true_positives / (true_positives + false_positives) if (true_positives + false_positives) > 0 else 0
recall = true_positives / (true_positives + false_negatives) if (true_positives + false_negatives) > 0 else 0
precisions.append(precision)
recalls.append(recall)
return precisions, recalls
def plot(self):
precisions, recalls = self.precision_recall_curve()
plt.plot(recalls, precisions, marker='.')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('P-R Curve')
plt.show()
```
使用示例:
```python
# 实例化 PRCurve 类,传入真实标签和预测分数
y_true = [1, 0, 1, 1, 0, 0, 1]
y_scores = [0.9, 0.6, 0.8, 0.7, 0.4, 0.3, 0.5]
pr_curve = PRCurve(y_true, y_scores)
# 绘制 P-R 曲线
pr_curve.plot()
```
这段代码实现了一个P-R曲线类,其中`y_true`是真实的标签,`y_scores`是预测的分数。`precision_recall_curve`方法计算并返回精确率和召回率的列表,`plot`方法用于绘制P-R曲线。你可以根据你的实际需求进行修改和优化。
阅读全文