precision-recall曲线python代码实现
时间: 2023-09-14 14:12:54 浏览: 105
好的,以下是一个简单的 precision-recall 曲线的 Python 代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成模拟数据
predictions = np.random.rand(100)
labels = np.random.randint(2, size=100)
# 计算精确度和召回率
tp = np.sum(np.logical_and(predictions == 1, labels == 1))
fp = np.sum(np.logical_and(predictions == 1, labels == 0))
tn = np.sum(np.logical_and(predictions == 0, labels == 0))
fn = np.sum(np.logical_and(predictions == 0, labels == 1))
precision = tp / (tp + fp)
recall = tp / (tp + fn)
# 计算不同阈值下的精确度和召回率,并绘制曲线
thresholds = np.arange(0, 1.01, 0.01)
precisions = []
recalls = []
for t in thresholds:
pred = np.where(predictions >= t, 1, 0)
tp = np.sum(np.logical_and(pred == 1, labels == 1))
fp = np.sum(np.logical_and(pred == 1, labels == 0))
fn = np.sum(np.logical_and(pred == 0, labels == 1))
p = tp / (tp + fp) if tp + fp != 0 else 0
r = tp / (tp + fn) if tp + fn != 0 else 0
precisions.append(p)
recalls.append(r)
plt.plot(recalls, precisions)
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.title("Precision-Recall Curve")
plt.show()
```
在这个例子中,我们生成了一些随机的二元标签和预测值,然后计算了一个阈值下的精确度和召回率,最后计算了不同阈值下的精确度和召回率,并绘制了 precision-recall 曲线。
阅读全文