機械学習のメトリクス2【AAAMLP】
AAAMLP
前回に引き続き、機械学習のメトリクス、評価指標について学んだことを記録します。
AAAMLP (Approaching (Almost) Any Machine Learning Problem)という書籍で勉強した内容の整理です。
この書籍は多くの言語に翻訳されていて、2021年8月に「Kaggle Grandmasterに学ぶ 機械学習 実践アプローチ」として日本語版も発売されています。
Metrics
今回は、マルチクラス問題に関する評価指標についてまとめます。 PrecisionとF1を書いていますが、Recall、AUC、Log Lossについても同様に計算できます。
Macro Precision
全クラスのPrecisionを計算し、その平均をとったものです。
def macro_precision(y_true, y_pred): num_classes = len(np.unique(y_true)) precision = 0 for class_ in range(num_classes): temp_true = [1 if p == class_ else 0 for p in y_true] temp_pred = [1 if p == class_ else 0 for p in y_pred] tp = true_positive(temp_true, temp_pred) fp = false_positive(temp_true, temp_pred) temp_precision = tp / (tp + fp) precision += temp_precision precision /= num_classes return precision
Micro Precision
クラスごとのTP、FPの和を計算し、そこからPrecision を計算します。
def micro_precision(y_true, y_pred): num_classes = len(np.unique(y_true)) tp = 0 fp = 0 for class_ in range(num_classes): temp_true = [1 if p == class_ else 0 for p in y_true] temp_pred = [1 if p == class_ else 0 for p in y_pred] tp += true_positive(temp_true, temp_pred) fp += false_positive(temp_true, temp_pred) precision = tp / (tp + fp) return precision
Weighted Precision
Macro Precisionと同じ計算だが、各クラスのサンプル数で重みづけをします。
from collections import Counter def weighted_precision(y_true, y_pred): num_classes = len(np.unique(y_true)) class_counts = Counter(y_true) precision = 0 for class_ in range(num_classes): temp_true = [1 if p == class_ else 0 for p in y_true] temp_pred = [1 if p == class_ else 0 for p in y_pred] tp = true_positive(temp_true, temp_pred) fp = false_positive(temp_true, temp_pred) temp_precision = tp / (tp + fp) weighted_precision = class_counts[class_] * temp_precision precision += weighted_precision overall_precision = precision / len(y_true) return overall_precision
Weighted F1
各クラスのF1の各クラスのサンプル数による重み付き平均です。
from collections import Counter def weighted_f1(y_true, y_pred): num_classes = len(np.unique(y_true)) class_counts = Counter(y_true) f1 = 0 for class_ in range(num_classes): temp_true = [1 if p == class_ else 0 for p in y_true] temp_pred = [1 if p == class_ else 0 for p in y_pred] p = precision(temp_true, temp_pred) r = recall(temp_true, temp_pred) if p + r != 0: temp_f1 = 2 * p * r / (p + r) else: temp_f1 = 0 weighted_f1 = class_counts[class_] * temp_f1 f1 += weighted_f1 overall_f1 = f1 / len(y_true) return overall_f1
Confusion Matrix
マルチクラスの場合のConfusion Matrixです。
左上から右下へのななめのラインのみ埋まるものが、完璧なConfusion Matrixです。
Conclusion
今回は、マルチクラス問題に対する評価指標をまとめました。
今回のAAAMLPを使った勉強では、マクロ・ミクロの意味や、使い道に関する違いはわかりませんでした。 これに関しては、今後どこかで補強したいと思います。
Link
GitHub - abhishekkrthakur/approachingalmost: Approaching (Almost) Any Machine Learning Problem