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
相关推荐
没有梦想的咸鱼185-1037-1663几秒前
AI大模型支持下的:CMIP6数据分析与可视化、降尺度技术与气候变化的区域影响、极端气候分析
人工智能·python·深度学习·机器学习·chatgpt·数据挖掘·数据分析
柠檬味拥抱21 分钟前
基于自适应信号处理的AI Agent多任务协同控制方法研究
人工智能
唐丙斯城38 分钟前
新能源汽车热管理仿真:蒙特卡洛助力神经网络训练
人工智能·神经网络·汽车
楚禾Noah1 小时前
【设计模式实战】原型模式 + 工厂模式:AI Agent 配置中心
人工智能·设计模式·原型模式
灵智工坊LingzhiAI2 小时前
基于深度学习的中草药识别系统:从零到部署的完整实践
人工智能·深度学习
今天也要学习吖2 小时前
Azure TTS Importer:一键导入,将微软TTS语音接入你的阅读软件!
人工智能·学习·microsoft·ai·大模型·aigc·azure
星期天要睡觉2 小时前
(纯新手教学)计算机视觉(opencv)实战八——四种边缘检测详解:Sobel、Scharr、Laplacian、Canny
人工智能·opencv·计算机视觉
一念&3 小时前
今日科技热点 | 量子计算突破、AI芯片与5G加速行业变革
人工智能·科技·量子计算
2501_924731113 小时前
智慧矿山误报率↓83%!陌讯多模态融合算法在矿用设备监控的落地优化
人工智能·算法·目标检测·视觉检测
attitude.x3 小时前
GEO优化供应商:AI搜索时代的“答案”构建与移山科技的引领,2025高性价比实战指南
人工智能·科技