AI/TensorFlow, PyTorch, Keras, Scikit
Confusion Matrix in python
JAYNUX
2017. 8. 3. 14:14
Confusion Matrix in python
Tensorflow
를 이용한 prediction 결과를 평가하기 위해서 Confusion Matrix
을 이용한다.
단순 Accuracy
에 대해서는 어느정도 문제가 발생하기 때문이다.
아래의 두 package를 각각 이용할 수도 있다.
scikit
scikit
package를 이용한 방법이 존재한다.
특정 값만 표시해 줄 수도 있고 Confusion Matrix
를 표현할 수도 있다.
# Import packages
from sklearn.metrics import classification_report
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
# Data
y_true = [1, 1, 0, 1, 0]
y_pred = [1, 1, 1, 0, 0]
target_names = ['false', 'true']
print(classification_report(y_true, y_pred, target_names=target_names))
precision_score(y_true, y_pred, average='binary',pos_label=1)
recall_score(y_true, y_pred, average='binary',pos_label=1)
실행 결과
precision recall f1-score support
false 0.50 0.50 0.50 2
true 0.67 0.67 0.67 3
avg / total 0.60 0.60 0.60 5
precision: 0.66666666666666663
recall: 0.66666666666666663
Pandas
import pandas as pd
y_true = pd.Series([2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2])
y_pred = pd.Series([0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2])
pd.crosstab(y_true, y_pred, rownames=['True'], colnames=['Predicted'], margins=True)
Result
Predicted 0 1 2 All
True
0 3 0 0 3
1 0 1 2 3
2 2 1 3 6
All 5 2 5 12