3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで混合行列からF値を算出する

Last updated at Posted at 2018-02-11

機械学習のモデル評価で使う「混合行列」から、「F値(F1値)」を算出するスクリプトです。

F値計算モデルの参考サイト:
機械学習で使う指標総まとめ - 多クラス分類

ソースコード

calculation_f1.py
import numpy as np

input_matrix = [ [2, 1, 0],[1, 6, 2],[0, 0, 3] ]

# input_matrix = [ [2, 1, 0], 
#                  [1, 6, 2], 
#                   [0, 0, 3] ]


def calculation_f1(input_matrix):

    confusion_matrix = np.array(input_matrix, dtype = 'float')

    matrix_len = len(confusion_matrix)
    col_sum = np.sum(confusion_matrix, axis=1)
    row_sum = np.sum(confusion_matrix, axis=0)

    F1_list = []

    for i in range(0, matrix_len):        
        Precision = confusion_matrix[i][i] / (confusion_matrix[i][i] + (col_sum[i] - confusion_matrix[i][i]))
        Recall = confusion_matrix[i][i] / (confusion_matrix[i][i] + (row_sum[i] - confusion_matrix[i][i]))
        F1 = (2*Precision*Recall) / (Precision+Recall)
        F1_list.append(F1)

    return sum(F1_list)/matrix_len

print("F value: " + str(calculation_f1(input_matrix)))

実行結果

F value: 0.7222222222222222

scikit-learnでF値のログを取り忘れた為に書きました。
皆さんもログの収集漏れには、くれぐれもお気をつけください...

3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?