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 小时前
AI Agent 开发踩坑记:口播功能非得用 APP 原生实现吗?
前端·人工智能·agent
蝎子莱莱爱打怪3 小时前
DSpark 讲透:DeepSeek 不换模型,硬把 V4 提速 85%,是怎么做到的?
人工智能·面试·程序员
巫山老妖4 小时前
置身AI内
人工智能
IT_陈寒6 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
vanuan7 小时前
两个AI智能体第一次对话-A2A双Agent协作实战
人工智能
kfaino9 小时前
码农的AI翻身(四)你好,我叫 Attention
人工智能·后端
雨落Re11 小时前
如何设计一个高质量Skill
人工智能
Token炼金师11 小时前
大模型权重文件全指南:从格式选择到优化实战
人工智能
阿牛哥_GX11 小时前
CDP 浏览器操控原理:让脚本接管你的浏览器
人工智能
ThreeS11 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python