python sklearn 小工具整理

 

测试训练数据集划分

https://blog.csdn.net/sinat_26917383/article/details/77917881    参考链接

 

混淆矩阵计算

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' python sklearn 混淆矩阵计算'

__author__ = 'qfr'

from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import numpy as np


y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
label = ["ant", "bird", "cat"]
cm = confusion_matrix(y_true, y_pred, labels=label)

# 热度图,后面是指定的颜色块,可设置其他的不同颜色
plt.imshow(cm, cmap=plt.cm.Blues)
plt.colorbar()

# label 坐标轴标签说明
indices = range(len(cm))
# 第一个是迭代对象,表示坐标的显示顺序,第二个参数是坐标轴显示列表
plt.xticks(indices, label)
plt.yticks(indices, label)

# plt.rcParams两行是用于解决标签不能显示汉字的问题
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.xlabel(r'预测值')
plt.ylabel(r'真实值')
plt.title(r'混淆矩阵')

# 显示数据
for first_index in range(len(cm)):    #第几行
    for second_index in range(len(cm[first_index])):    #第几列
        plt.text(first_index, second_index, cm[first_index][second_index])

plt.show()
  

  

划分正确率计算

from sklearn.metrics import accuracy_score
print("正确率:", accuracy_score(y_true, y_pred))
# 正确率: 0.6666666666666666

  

from sklearn.metrics import classification_report
print(classification_report(y_true, y_pred, target_names=label))

 

sklearn中f1-score的简单使用

简单代码

from sklearn.metrics import f1_score                  # 导入f1_score
f1_score(y_test,y_predict, average='micro')            # 调用并输出计算的值
f1_score(y_test,y_predict, average='macro')
解释

其中

  • y_test: 真实的数据集切分后的测试y的值
  • y_predict: 预测值
    avarage: 数值计算的两种不同方式

f1_score

计算公式
f1_score = (2 * Recall * Presision) / (Recall + Presision)
意义
假设Recall 与 Presision 的权重一样大, 求得的两个值的加权平均书
sklearn中的使用

导入: from sklearn.metrics import f1_score

其中:average 的取值:

  • micro: 通过计算正确,错误和否定的总数来全局计算指标
  • macro: 计算每个标签的指标,并找到其未加权平均值。这没有考虑标签不平衡。

 

参考链接如下:

sklearn中的模型评估-构建评估函数

 

posted @ 2021-04-14 16:40  博客园—哆啦A梦  阅读(105)  评论(0)    收藏  举报