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
相关推荐
FF-Studio1 分钟前
【硬核数学】2. AI如何“学习”?微积分揭秘模型优化的奥秘《从零构建机器学习、深度学习到LLM的数学认知》
人工智能·深度学习·学习·机器学习·自然语言处理·微积分·高等数学
仙人掌_lz2 分钟前
深入理解蒙特卡洛树搜索(MCTS):python从零实现
人工智能·python·算法·ai·强化学习·rl·mcts
追逐☞5 分钟前
机器学习(14)——模型调参
人工智能·机器学习
犬余7 分钟前
告别Spring AI!我的Java轻量AI框架实践(支持多模型接入|注解式MCP架构|附开源地址)
java·人工智能·spring
Ro小陌15 分钟前
VisionPro自动化视觉开发实战:脚本编写、规范管理与高级调试
人工智能·microsoft·自动化
水花花花花花37 分钟前
离散文本表示
人工智能·机器人
Thanks_ks41 分钟前
Manus AI 突破多语言手写识别技术壁垒:创新架构、算法与应用解析
人工智能·迁移学习·应用场景·技术突破·多语言手写识别·manus ai·动态书写模型
whaosoft-14342 分钟前
w~自动驾驶合集1
人工智能
白熊18842 分钟前
【通用智能体】Lynx :一款基于终端的纯文本网页浏览器
前端·人工智能·chrome·通用智能体
计算机毕设源码分享8888881 小时前
番茄采摘机器人的视觉系统设计
人工智能·算法·机器人