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
相关推荐
人工智能技术咨询.8 分钟前
深度学习—卷积神经网络
人工智能
机器之心8 分钟前
Manus被收购,智谱也定了8天后上市
人工智能·openai
王中阳Go24 分钟前
手把手教你用 Go + Eino 搭建一个企业级 RAG 知识库(含代码与踩坑)
人工智能·后端·go
Coder个人博客1 小时前
Llama.cpp 整体架构分析
人工智能·自动驾驶·llama
江上鹤.1481 小时前
Day 50 CBAM 注意力机制
人工智能·深度学习
deephub1 小时前
大规模向量检索优化:Binary Quantization 让 RAG 系统内存占用降低 32 倍
人工智能·大语言模型·向量检索·rag
人工智能培训1 小时前
深度学习—卷积神经网络(1)
人工智能·深度学习·神经网络·机器学习·cnn·知识图谱·dnn
ㄣ知冷煖★1 小时前
【Google系列】AI智能体技术白皮书
人工智能·agent
新加坡内哥谈技术1 小时前
阿尔茨海默症的成因与风险因素到模型与干预分析
人工智能
张张张三丰1 小时前
【文献】金融市场发展与企业风险管理:来自上海原油期货上市的证据
人工智能·# 相关知识