概要
作成した判別モデルの評価について説明します。
はじめに
評価には、以下の指標を用いられます。
- Accuracy(正確度)
- 正例、負例の重要度が同じ場合
- 正例、負例の重要度が同じ場合
- Recall(再現性)
- 検出率の精度を重要視する場合
- 検出率の精度を重要視する場合
- Precision(適合率)
- 見落とし率を重要視する場合
- 見落とし率を重要視する場合
- F-measure(F値)
- ビジネスの要件でRecallとPrecisionのどちらとも言えない場合
- ビジネスの要件でRecallとPrecisionのどちらとも言えない場合
- AUC
- モデルの性能を評価したい場合
【ROCカーブ】
1-4は、混同行列と合わせて確認されます。
5はROC曲線と合わせて確認されます。
不均衡データの場合、
1-4だと正しく評価できないので、5のAUCを用いて評価します。
ビジネスの要件に合わせて、どの指標を使用して評価するかが大切になりますので、
クライアントのビジネスを理解しておく必要があります。
実装
ROC/AUC
irisデータセットを使用した実装例になります。
import numpy as np import matplotlib.pyplot as plt from itertools import cycle from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.model_selection import train_test_split from sklearn.preprocessing import label_binarize from sklearn.multiclass import OneVsRestClassifier from scipy import interp from sklearn.metrics import roc_auc_score # Import some data to play with iris = datasets.load_iris() X = iris.data y = iris.target # Binarize the output y = label_binarize(y, classes=[0, 1, 2]) n_classes = y.shape[1] # Add noisy features to make the problem harder random_state = np.random.RandomState(0) n_samples, n_features = X.shape X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] # shuffle and split training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, random_state=0) # Learn to predict each class against the other classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=random_state)) y_score = classifier.fit(X_train, y_train).decision_function(X_test) # Compute ROC curve and ROC area for each class fpr = dict() tpr = dict() roc_auc = dict() for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel()) roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
プロット
plt.figure() lw = 2 plt.plot(fpr[2], tpr[2], color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[2]) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show()
混同行列
scikitlearnとseabornを使ってプロットします。
from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix #Fit the model logreg = LogisticRegression(C=1e5) logreg.fig(X,y) #Generate predictions with the model using our X values y_pred = logreg.predict(X) #Get the confusion matrix cf_matrix = confusion_matrix(y, y_pred) #Plot import seaborn as sns sns.heatmap(cf_matrix, annot=True)
さいごに
評価指標について解説しました。
よくPrecisionとRecallの計算式がどっちかわからなくなります。