Precision又叫查准率,Recall又叫查全率。這兩個指標共同衡量才能評價模型輸出結果。
- TP: 預測為1(Positive),實際也為1(Truth-預測對了)
- TN: 預測為0(Negative),實際也為0(Truth-預測對了)
- FP: 預測為1(Positive),實際為0(False-預測錯了)
- FN: 預測為0(Negative),實際為1(False-預測錯了)
總的樣本個數為:TP+TN+FP+FN。
Accuracy/Precision/Recall的定義
Accuracy = (預測正確的樣本數)/(總樣本數)=(TP+TN)/(TP+TN+FP+FN)
Precision = (預測為1且正確預測的樣本數)/(所有預測為1的樣本數) = TP/(TP+FP)
Recall = (預測為1且正確預測的樣本數)/(所有真實情況為1的樣本數) = TP/(TP+FN)
如何理解Precision/Recall
假設100癌症訓練集中,只有1例為癌症。如果模型永遠預測y=0,則模型的Precision=99/100,很高。但Recall=0/1=0,非常低。
所以單純用Precision來評價模型是不完整的,評價模型時必須用Precision/Recall兩個值。
如何理解F1
假設我們得到了模型的Precision/Recall如下
| Precision | Recall |
|---|---|
| Algorithm1 | 0.5 |
| Algorithm2 | 0.7 |
| Algorithm3 | 0.02 |
但由於Precision/Recall是兩個值,無法根據兩個值來對比模型的好壞。有沒有一個值能綜合Precision/Recall呢?有,它就是F1。
F1 = 2*(Precision*Recall)/(Precision+Recall)
| Algorithm | F1 |
|---|---|
| Algorithm1 | 0.444 |
| Algorithm2 | 0.175 |
| Algorithm3 | 0.039 |
只有一個值,就好做模型對比了,這里我們根據F1可以發現Algorithm1是三者中最優的。
分類閾值對Precision/Recall的影響
做二值分類時,我們認為,若h(x)>=0.5,則predict=1;若h(x)<0.5,則predict=0。這里0.5就是分類閾值。
增加閾值,我們會對預測值更有信心,即增加了查准率。但這樣會降低查全率。(High Precision, Low Recall)
減小閾值,則模型放過的真例就變少,查全率就增加。(Low Precision, High Recall)
from sklearn.metrics import classification_report y=[0,1,2,2,2] y_=[0,0,2,2,1] # sklearn.metrics.classification_report(y_true,y_pred,labels=None,target_names=None,sample_weight=None,digits=2) # y_true,y_pred 1d array-like # labels shape=[n_labels] label索引的列表,需要在report中包含的 # target_names 匹配label的可選的display的名字 # sample_weight shape=[n_sample] 可選的sample weights # digits int 輸出的浮點數的個數 # returns 返回每個類別的precision recall F1 target_names=['class 0','class 1','class 2'] print(classification_report(y,y_,target_names=tar
class 0 0.500 1.000 0.667 1 class 1 0.000 0.000 0.000 1 class 2 1.000 0.667 0.800 3 avg / total 0.700 0.600 0.613 5
