栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

211209-自定义Sklearn混淆矩阵及参数理解

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

211209-自定义Sklearn混淆矩阵及参数理解

在计算转移矩阵的时候,预测类别可能是实际类别的子集,sklearn自带的混淆矩阵不能直接使用,此处自定义,并进一步理解sklearn中混淆矩阵的定义。

混淆矩阵

Matlab中X-Target, Y-Output (link)

Sklearn中X-Output, Y-Target (link)

  • 代码
import numpy as np
from sklearn.metrics import confusion_matrix

def my_confusion_matrix(y_true, y_pred, cat_num = 2, normalize=None):
    cm = np.zeros((cat_num, cat_num))
    for (t,p) in zip(y_true, y_pred):
        cm[t, p] += 1
    if normalize is None:
        pass
    if normalize == 'pred':
        cm = cm/cm.sum(axis=0, keepdims=True)
    if normalize == 'true':
        cm = cm/cm.sum(axis=1, keepdims=True)
    if normalize == 'all':
        cm = cm/np.sum(cm)
    return cm


# Test 1
y_true = [0, 0, 0, 1, 1, 1, 1, 1]
y_pred = [0, 1, 0, 1, 0, 1, 0, 1]

cm_none = confusion_matrix(y_true, y_pred, normalize=None)
cm_pred = confusion_matrix(y_true, y_pred, normalize='pred')
cm_true = confusion_matrix(y_true, y_pred, normalize='true')
cm_all  = confusion_matrix(y_true, y_pred, normalize='all')


print('None n', cm_none,'n')
print('Pred - Divide by sum of Col n', cm_pred,'n')
print('True - Divide by sum of Row n', cm_true,'n')
print('All- - Divide by sum of Mat n', cm_all, 'n')


# Test 2
cm_none = my_confusion_matrix(y_true, y_pred, normalize=None)
cm_pred = my_confusion_matrix(y_true, y_pred, normalize='pred')
cm_true = my_confusion_matrix(y_true, y_pred, normalize='true')
cm_all  = my_confusion_matrix(y_true, y_pred, normalize='all')


print('None n', cm_none,'n')
print('Pred - Divide by sum of Col n', cm_pred,'n')
print('True - Divide by sum of Row n', cm_true,'n')
print('All- - Divide by sum of Mat n', cm_all, 'n')

  • 结果
None 
 [[2 1]
 [2 3]] 

Pred - Divide by sum of Col 
 [[0.5  0.25]
 [0.5  0.75]] 

True - Divide by sum of Row 
 [[0.66666667 0.33333333]
 [0.4        0.6       ]] 

All- - Divide by sum of Mat 
 [[0.25  0.125]
 [0.25  0.375]] 

None 
 [[2. 1.]
 [2. 3.]] 

Pred - Divide by sum of Col 
 [[0.5  0.25]
 [0.5  0.75]] 

True - Divide by sum of Row 
 [[0.66666667 0.33333333]
 [0.4        0.6       ]] 

All- - Divide by sum of Mat 
 [[0.25  0.125]
 [0.25  0.375]] 


Ref:

  • https://scikit-learn.org/stable/modules/model_evaluation.html#confusion-matrix
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/655494.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号