matplotlibでROC曲線を描画する(1. import編)
ROC曲線をpython3で描画したいと思ったときに,用意すればいいもの,コード,を説明する.今回は何をimport し, これの入力はなにか,を説明する.
1つの記事を大きくするするのは可読性が低くなるので分割する.
全体の流れ(今回は1)
コードサンプルは次の通り
処理のイメージは次の通り
from sklearn.metrics import roc_curve from sklearn.metrics import auc y_true = [用意してあげる] (ここは2で説明する) y_score = [用意してあげる] (ここは2で説明する) fpr, tpr, th = roc_curve(y_true, y_score) auc_value = auc(fpr, tpr) (描画:3で説明する)
ROC曲線描画・AUC計算に必要なライブラリをimport する
2つのライブラリをimport する
from sklearn.metrics import roc_curve from sklearn.metrics import auc
sklearn.metrics.roc_curve(y_true, y_score, pos_label=None, sample_weight=None, drop_intermediate=True)
とある.重要なのは, y_true
と y_score
の2つで, ドキュメントには次のような説明がある.
y_true : array, shape = [n_samples] True binary labels in range {0, 1} or {-1, 1}. If labels are not binary, pos_label should be explicitly given. y_score : array, shape = [n_samples] Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by “decision_function” on some classifiers).
つまり, y_true
は(0,1)の二値ラベル, もしくは(-1, 1)のarrayである.
y_score
は y_true
に対応した何らかのスコア.これは連続値でOK.
データ準備編で詳細は述べるが, イメージとしては
y_true | y_score |
---|---|
0 | 1.0 |
0 | 1.5 |
0 | 1.3 |
.. | ... |
1 | 1.6 |
1 | 1.9 |
1 | 2.2 |
1 | 0.3 |
この関数の返り値は
fpr : array, shape = [>2] <-- False Positive Rate tpr : array, shape = [>2] <-- True Positive Rate thresholds : array, shape = [n_thresholds] <-- 閾値
次のauc計算は, ドキュメントのページによると
sklearn.metrics.auc(x, y, reorder=False)
とあり, x,yはそれぞれ
x : array, shape = [n] x coordinates. y : array, shape = [n] y coordinates.
これは難しくなく, 何らかの2つの行列をいれればいいんだな~ということがわかる.ROC曲線を描画するときは, 上で説明したroc_curve
の返り値をそれぞれxに False positive rate fpr
を, yにTrue positive rate tpr
を入力とする.
この関数の返り値は,
Returns: auc : float <-- float型のAUC値が1つだけ
float型のAUC値が1つだけ返ってくる. 1つのROC曲線に対して1つのAUC値が返ってくる.
今回のことからわかること
y_true
, y_score
を用意してあげて,import した roc_curve
の入力とする. すると, fpr, tprが返ってくる.
このfpr, tprを入力として, import したauc()にいれてやるとauc値が出てくる.
流れを再掲する.
from sklearn.metrics import roc_curve from sklearn.metrics import auc y_true = [用意してあげる] y_score = [用意してあげる] fpr, tpr, th = roc_curve(y_true, y_score) auc_value = auc(fpr, tpr)
必要なデータを用意すれば,ROC曲線を描画するための素となるfpr, tpr, aucを計算することは容易だ.