帮我写一个ROC曲线的代码
时间: 2024-06-12 15:07:45 浏览: 13
以下是一个示例代码,用于绘制二分类问题的ROC曲线:
```python
import numpy as np
import matplotlib.pyplot as plt
# true labels and predicted scores for binary classification
y_true = np.array([0, 0, 0, 1, 1, 1])
y_score = np.array([0.1, 0.2, 0.3, 0.7, 0.8, 0.9])
# sort the scores and corresponding labels in descending order
sorted_indices = np.argsort(y_score)[::-1]
y_true_sorted = y_true[sorted_indices]
y_score_sorted = y_score[sorted_indices]
# initialize variables for ROC curve
tp = 0 # true positives
fp = 0 # false positives
tn = np.sum(y_true == 0) # true negatives
fn = np.sum(y_true == 1) # false negatives
tpr_list = [] # true positive rate
fpr_list = [] # false positive rate
# loop through each score and update variables
for i in range(len(y_score_sorted)):
if y_true_sorted[i] == 1:
tp += 1
fn -= 1
else:
fp += 1
tn -= 1
tpr = tp / (tp + fn)
fpr = fp / (fp + tn)
tpr_list.append(tpr)
fpr_list.append(fpr)
# add (0, 0) and (1, 1) points to the ROC curve
tpr_list.insert(0, 0)
fpr_list.insert(0, 0)
tpr_list.append(1)
fpr_list.append(1)
# plot the ROC curve
plt.plot(fpr_list, tpr_list)
plt.title('ROC Curve')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.show()
```
这个示例代码假设已经有了一个由真实标签和预测得分组成的numpy数组 `y_true` 和 `y_score`。首先,这些数据被排序,并对应的标签被重新排序。接下来,使用对应的真实标签和预测得分,逐个计算真正率(TPR)和假正率(FPR)的值。最后,将FPR和TPR值的列表用于绘制ROC曲线。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)