Yukyukuon / blog

博客的文章
1 stars 0 forks source link

数据分析 #22

Open Yukyukuon opened 1 year ago

Yukyukuon commented 1 year ago

记录一些评估机器学习算法性能,结果分析的帖子

混淆矩阵(Confusion Matrix)

在机器学习领域,混淆矩阵(confusion matrix),又称为可能性表格或是错误矩阵。它是一种特定的矩阵用来呈现算法性能的可视化效果,通常是监督学习(非监督学习,通常用匹配矩阵:matching matrix)。其每一列代表预测值,每一行代表的是实际的类别。这个名字来源于它可以非常容易的表明多个类别是否有混淆(也就是一个class被预测成另一个class)。

Table of confusion

真实\预测 P (0) N (1)
P (0) TP FN
N (1) FP TN

TP(True Positive): 真实为0,预测也为0
FN(False Negative): 真实为0,预测为1
FP(False Positive): 真实为1,预测为0
TN(True Negative): 真实为1,预测也为1

:分类模型总体判断的准确率(包括了所有class的总体准确率)
:预测为0的准确率
:真实为0的准确率 :对于某个分类,综合了Precision和Recall的一个判断指标,F1-Score的值是从0到1的,1是最好,0是最差

代码实现

这里使用的是IMDB的测试数据,并用IMDB例子的网络对数据进行预测

# model.predict() 对测试数据集(x_test)进行预测每个样本最后一个神经元的值
model.predict(x_test)
# model.predict_classes() 预测每个样本最后会被分类在哪一类
prediction = model.predict_classes(x_test)
# 查看分类结果是一个 二元张量(向量),但是编写混淆矩阵是需要一维张量
prediction.shape
# 将预测结果转化成一维张量
prediction.reshape(-1)
# 查看结果,确实是一维张量
prediction.reshape(-1).shape
# y_test 是test_data的标签 ,是一维张量
y_test.shape

生成混淆矩阵

import pandas as pd
# 先写第0个轴(Y轴,为y_test),再写第1个轴(X轴,为prediction.reshape(-1)),然后写rounames和colnames
pd.crosstab(y_test, prediction.reshape(-1),
            rownames=['label'], colnames=['predict'])

Table of confusion

计算各项数据

from sklearn.metrics import classification_report
print(classification_report(y_test, prediction))