我正在尝试绘制ROC曲线,以评估乳腺癌数据集的隔离林的准确性。我从混淆矩阵中计算出“真阳性率”(TPR)和“假阳性率”(FPR)。但是,我不了解TPR和FPR如何以矩阵形式而不是单个整数值形式出现。 ROC曲线似乎仅适用于矩阵形式的FPR和TPR(我也尝试过手动编写用于计算FPR和TPR的代码)。
TPR和FPR值是否始终以矩阵形式出现?
无论哪种方式,我的ROC曲线都是一条直线。为什么会这样呢?
混淆矩阵:
from sklearn.metrics import confusion_matrix
cnf_matrix = confusion_matrix(y, y_pred_test1)
O / P:
> [[ 5 25]
> [ 21 180]]
真阳性和假阳性:(此外,为什么这些值直接从混淆矩阵中提取?)
F_P = cnf_matrix.sum(axis=0) - np.diag(cnf_matrix)
F_N = cnf_matrix.sum(axis=1) - np.diag(cnf_matrix)
T_P = np.diag(cnf_matrix)
T_N = cnf_matrix.sum() - (FP + FN + TP)
F_P = F_P.astype(float)
F_N = F_N.astype(float)
T_P = T_P.astype(float)
T_N = T_N.astype(float)
O / P:
False Positive [21. 25.] False Negative [25. 21.] True Positive [ 5. 180.] True Negative [180. 5.]
TPR和FPR:
tp_rate = TP/(TP+FN)
fp_rate = FP/(FP+TN)
O / P:
TPR : [0.16666667 0.89552239] FPR [0.10447761 0.83333333]
ROC曲线:
from sklearn import metrics
import matplotlib.pyplot as plt
plt.plot(fp_rate,tp_rate)
plt.show()
O / P:
答案 0 :(得分:2)
混淆矩阵本质上为您提供了ROC曲线上的单个点。要构建“完整” ROC曲线,您将需要一个概率列表,然后可以通过改变用于确定类别预测以确定每个实例所属的类别的“阈值”来绘制ROC曲线。
在简单情况下(当ROC曲线只有一个点时),可以通过外推到原点和点(1,1)来绘制ROC曲线:
disablePrependAtCopy
,ROC曲线如下:
答案 1 :(得分:2)
confusion_matrix()
函数仅为您提供正确/错误分类的点,但没有提供有关模型对数据点进行错误分类时确信程度的信息。
此信息用于创建ROC曲线(用于测量模型根据每个数据点对特定类别的可能性对每个数据点进行排名的能力。
相反,请使用或
decision_function()
函数来计算模型对每个数据点是否为异常的置信度。然后,使用score_samples()
获取绘制曲线本身所需的点。
这里是乳腺癌数据集的一个例子。
from sklearn.datasets import load_breast_cancer
X, y = load_breast_cancer(return_X_y=True)
from sklearn.ensemble import IsolationForest
clf = IsolationForest(behaviour='new', max_samples=100,
random_state=0, contamination='auto')
clf.fit(X)
y_pred = clf.score_samples(X)
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y,y_pred)
import matplotlib.pyplot as plt
plt.plot(fpr, tpr, 'k-', lw=2)
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.show()