机器学习课本与实战

第二章 模型评估与选择(对应西瓜书)

  • MSE RMSE R2
from sklearn.metrics import mean_squared_error, r2_score
import numpy as np 
print(f"均方误差(MSE):{mean_squared_error(result, test_y)}")
print(f"根均方误差(RMSE):{np.sqrt(mean_squared_error(result, test_y))}")
print(f"测试集R^2:{r2_score(test_y, result)}")
  • 混淆矩阵

混淆矩阵也称误差矩阵,是表示精度评价的一种标准格式,用n行n列的矩阵形式来表示。具体评价指标有总体精度、制图精度、用户精度等,这些精度指标从不同的侧面反映了图像分类的精度。在人工智能中,混淆矩阵(confusion matrix)是可视化工具,特别用于监督学习,在无监督学习一般叫做匹配矩阵。在图像精度评价中,主要用于比较分类结果和实际测得值,可以把分类结果的精度显示在一个混淆矩阵里面。混淆矩阵是通过将每个实测像元的位置和分类与分类图像中的相应位置和分类相比较计算的。

TP(True Positive):真实值是positive,模型认为是positive的数量,即模型预测正确的正例数量。

FN(False Negative):真实值是positive,模型认为是negative的数量,即模型预测错误的正例数量,这是统计学上的第二类错误(Type II Error)。

FP(False Positive):真实值是negative,模型认为是positive的数量,即模型预测错误的负例数量,这是统计学上的第一类错误(Type I Error)。

TN(True Negative):真实值是negative,模型认为是negative的数量,即模型预测正确的负例数量。

在这里插入图片描述

为了便于大家记忆,可以把混淆矩阵中的P和N看成模型的预测结果positive和negative,这里的positive和negative不表示好和坏,只表示模型的类别1(positive)和0(negative)。T和F看成模型预测是否正确,模型预测正确标记为T,预测错误标记为F。比如TP表示模型预测为positive,且模型预测正确的样本数量,即样本实际类别为positive,模型预测类别为positive的样本数量。FP表示模型预测为positive,且模型预测错误的样本数量,即样本实际类别为negative,模型错误地预测成了positive的样本数量。

对于预测性分类模型,我们希望模型的预测结果越准越好,即混淆矩阵中TP、TN的值越大越好,相应FP、FN的值越小越好。但是,混淆矩阵里统计的是数量,在数据量很大的情况下很难一眼判断出模型的优劣。因此,在混淆矩阵的基本统计结果上又衍生了如下4个指标(可以理解为二级指标,类似于特征工程里的衍生变量):

在这里插入图片描述
查准率P:图中的准确率
查全率R:图中的灵敏度

P-Q曲线

在很多情形札我们可根据学习器的预测结果对样例进行排序,排在前面的是学习器认为"最可能"是正例的样本?排在最后的则是学习器认为"最不可能"是正例的样本.按此顺序逐个把样本作为正例进行预测,则每次可以计算出当前的查全率、查准率以查准率为纵轴、查全率为横轴作图,就得到了查准率-查全率曲线,简称" P-R 曲线"显示该曲线的图称为" P-R图"

在这里插入图片描述

F1度量
在这里插入图片描述
在这里插入图片描述

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics import confusion_matrix, recall_score, classification_report
#加载数据
%matplotlib inline
date = pd.read_csv("data.csv", encoding="gbk")

在这里插入图片描述

def plot_confusion_matrix(cm, classes,normalize=False,title='Confusion matrix',cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')
    print(cm)
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)
    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
import itertools
cnf_matrix = confusion_matrix(date.flag, date.pred) #计算混淆矩阵
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix, classes = class_names, title = 'Confusion matrix')  #绘制混淆矩阵
np.set_printoptions(precision=2)
print('Accary:', (cnf_matrix[1,1]+cnf_matrix[0,0])/(cnf_matrix[1,1]+cnf_matrix[0,1]+cnf_matrix[0,0]+cnf_matrix[1,0]))
print('Recall:', cnf_matrix[1,1]/(cnf_matrix[1,1]+cnf_matrix[1,0]))     
print('Precision:', cnf_matrix[1,1]/(cnf_matrix[1,1]+cnf_matrix[0,1]))  
print('Specificity:', cnf_matrix[0,0]/(cnf_matrix[0,1]+cnf_matrix[0,0]))
plt.show()

sklearn.metrics.f1_score

from sklearn.metrics import f1_score
y_true = [0, 1, 2, 0, 1, 2]
y_pred = [0, 2, 1, 0, 0, 1]
f1_score(y_true, y_pred, average='macro')

f1_score(y_true, y_pred, average='micro')

f1_score(y_true, y_pred, average='weighted')

f1_score(y_true, y_pred, average=None)

y_true = [0, 0, 0, 0, 0, 0]
y_pred = [0, 0, 0, 0, 0, 0]
f1_score(y_true, y_pred, zero_division=1)

# multilabel classification
y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]]
y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]]
f1_score(y_true, y_pred, average=None)

【机器学习-模型评价】宏平均(macro avg)、微平均(micro avg)和加权平均(weighted avg)

  • ROC AUC
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set(font='SimHei',style='ticks')
 
from sklearn import datasets
digits = datasets.load_digits()
X = digits.data
y = digits.target.copy()
y[digits.target==9] = 1
y[digits.target!=9] = 0
 
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=666)
 
from sklearn.linear_model import LogisticRegression
log_reg = LogisticRegression()
log_reg.fit(X_train, y_train)
decision_scores = log_reg.decision_function(X_test)
 
from sklearn.metrics import roc_curve
fprs, tprs, thresholds = roc_curve(y_test, decision_scores)
plt.plot(fprs, tprs)
from sklearn.metrics import roc_auc_score
roc_auc_score(y_test, decision_scores) #AUC

-代价曲线
代价曲线是在出现非平衡代价的情况下才使用的。所有曲线最下方的面积越小,则代表模型越好。

第三章 线性模型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值