sklearn包中对于分类问题,如何计算accuracy和roc_auc_score?

1. 基础条件

python 复制代码
import numpy as np
from sklearn import metrics

y_true = np.array([1, 7, 4, 6, 3])
y_prediction = np.array([3, 7, 4, 6, 3])

2. accuracy_score计算

python 复制代码
acc = metrics.accuracy_score(y_true, y_prediction)

这个没问题

3. roc_auc_score计算

The binary and multiclass cases expect labels with shape (n_samples,) while the multilabel case expects binary label indicators with shape (n_samples, n_classes).

因此metrics.roc_auc_score对于multiclasses类的roc_auc_score计算,需要一个二维array,每一列是表示分的每一类,每一行是表示是否为此类。

python 复制代码
from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder(sparse=False)
enc.fit(y_true.reshape(-1, 1))
y_true_onehot = enc.transform(y_true.reshape(-1, 1))
y_predictions_onehot = \
    enc.transform(y_prediction.reshape(-1, 1))
bash 复制代码
In [201]: y_true_onehot
Out[201]: 
array([[1., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 1., 0., 0., 0.]])

In [202]: y_predictions_onehot
Out[202]: 
array([[0., 1., 0., 0., 0.],
       [0., 0., 0., 0., 1.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 1., 0., 0., 0.]])
bash 复制代码
In [204]: enc.categories_
Out[204]: [array([1, 3, 4, 6, 7])]

所以结合enc.categories_y_true_onehoty_truey_true_onehot的对应关系如下:

Class 1 3 4 6 7
true value: 1 1
true value: 7 1
true value: 4 1
true value: 6 1
true value: 3 1

因此,对于y_predictiony_prediction_onehot的对应关系就是如下:

Class 1 3 4 6 7
Prediction value: 3 1
Prediction value: 7 1
Prediction value: 4 1
Prediction value: 6 1
Prediction value: 3 1

这就解释了上述y_true_onehoty_prediction_onehot的返回结果。

python 复制代码
ensemble_auc = metrics.roc_auc_score(y_true_onehot,
                                     y_predictions_onehot)
bash 复制代码
In [200]: ensemble_auc
Out[200]: 0.875
相关推荐
虚假程序设计3 分钟前
pythonnet python图像 C# .NET图像 互转
开发语言·人工智能·python·opencv·c#·.net
AI王也29 分钟前
ChatGPT 4o 使用指南 (9月更新)
人工智能·chatgpt·prompt·aigc
望繁信科技32 分钟前
望繁信科技受邀出席ACS2023,为汽车行业数智化护航添翼
人工智能·企业数字化转型·流程挖掘·流程智能·数字北极星
木凳子a35 分钟前
给儿童掏耳朵用哪个好?儿童耳勺最建议买的五个牌子
人工智能·安全·信息可视化·智能家居·健康医疗
秋91 小时前
教师心理学能力研判:多维度视角下的分析,判断教师心理学知识能力强弱,并提出针对性意见
人工智能·心理学研判·教师心理学研判·心理学知识研判
中科微星1 小时前
相位型SLM硬件产品面型性能提升
图像处理·人工智能·深度学习
AI202408141 小时前
众数信科AI智能体政务服务解决方案——寻知智能笔录系统
人工智能·政务
生信宝典2 小时前
ROC和AUC也不是评估机器学习性能的金标准
人工智能·qt·机器学习
ShuQiHere2 小时前
【ShuQiHere】 探索计算机视觉的世界:从基础到应用
人工智能·计算机视觉
毕小宝2 小时前
TensorFlow 的基本概念和使用场景
人工智能·python·tensorflow