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
相关推荐
rocksun34 分钟前
为什么人工智能需要一种新的可观测性方法
人工智能
柠檬味拥抱36 分钟前
生成式物理引擎在人工智能训练中的关键作用与发展趋势研究
人工智能
新加坡内哥谈技术42 分钟前
Siri在WWDC中的缺席显得格外刺眼
人工智能·ios·wwdc
deephub1 小时前
提升长序列建模效率:Mamba+交叉注意力架构完整指南
人工智能·深度学习·时间序列·mamba·交叉注意力
神经星星1 小时前
入选 ICML 2025,清华/人大提出统一生物分子动力学模拟器 UniSim
人工智能·深度学习·机器学习
机器学习之心1 小时前
光伏功率预测 | BP神经网络多变量单步光伏功率预测(Matlab完整源码和数据)
人工智能·神经网络·matlab
layneyao1 小时前
Ray框架:分布式AI训练与调参实践
人工智能·分布式
vlln2 小时前
【论文解读】Search-R1:通过 RL 让 LLM 学会使用搜索引擎
人工智能·深度学习·神经网络·搜索引擎·transformer
alfred_torres2 小时前
CVPR 2025 MIMO: 支持视觉指代和像素grounding 的医学视觉语言模型
人工智能·语言模型·自然语言处理
程序员阿龙2 小时前
计算机毕业设计微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统源码+论文+PPT+讲解 基于微信小程序的题库系统设计与实现
微信小程序·分类·课程设计·在线答题·题库系统·错题本管理·试题分类