机器学习之性能度量-查准率和查全率计算(precision and recall)

"""
@author: JacksonKim
@filename: confusion_matrix.py
@start: 2021/02/01
@end:   2021/02/01
"""

import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier

'''
混淆矩阵是机器学习中总结分类模型预测结果的情形分析表,以矩阵形式将数据集中的记录按照真实的类别与分类模型预测的类别判断两个标准进行汇总:
1. TR:真正例,将正类预测为正类
2. FP: 假正例,将反例预测为正例
3. TN: 真反例,将反例预测为反例
4. FN: 假反例,将正例预测为反例
5. P:查准率, P = TP / (TP + FP)
6. R: 查全率, R = TP / (TP + FN)
'''


# 计算TP, 正例为1,反例为0
def TP(y_true, y_predict):
    assert len(y_true) == len(y_predict)  # assert断言函数,当表达式为false时触发异常
    return np.sum((y_true == 1) & (y_predict == 1))


# 计算FN
def FN(y_true, y_predict):
    assert len(y_true) == len(y_predict)
    return np.sum((y_true == 1) & (y_predict == 0))


# 计算FP
def FP(y_true, y_predict):
    assert len(y_true) == len(y_predict)
    return np.sum((y_true == 0) & (y_predict == 1))


# 计算TN
def TN(y_true, y_predict):
    assert len(y_true) == len(y_predict)
    return np.sum((y_true == 0) & (y_predict == 0))


# 生成混淆矩阵
def confusion_matrix(y_true, y_predict):
    return np.array([
        [TN(y_true, y_predict), FP(y_true, y_predict)],
        [FN(y_true, y_predict), TP(y_true, y_predict)]
    ])


# 获取数据集
def get_data():
    # 使用鸾尾花数据集和knn算法测试
    iris = datasets.load_iris()

    X = iris.data[:, :2]  # 取鸾尾花数据集每个元素(list)的前两个数
    Y = iris.target  # 获取鸾尾花数据集的分类

    # 画出原始数据的分类散点图
    # plt.scatter(X[Y == 0, 0], X[Y == 0, 1], color='r')
    # plt.scatter(X[Y == 1, 0], X[Y == 1, 1], color='b')
    # plt.scatter(X[Y == 2, 0], X[Y == 2, 1], color='g')
    # plt.show()

    # 选取原始数据集的两个分类做二分类任务
    iris_x = X[Y < 2]
    iris_y = Y[Y < 2]
    print(iris_x)
    print(iris_y)
    # 画出这两类数据的散点图
    plt.scatter(iris_x[iris_y == 0, 0], iris_x[iris_y == 0, 1], color='r')
    plt.scatter(iris_x[iris_y == 1, 0], iris_x[iris_y == 1, 1], color='b')
    # plt.show()
    return iris_x, iris_y


# 使用留出法处理数据
def train_test_split(x, y):
    shuffle_indexs = np.random.permutation(len(x))
    test_radio = 0.3  # 设置测试集比例
    test_size = int(len(x) * test_radio)  # 求出测试集大小
    # 求出训练/测试集
    test_indexs = shuffle_indexs[:test_size]
    train_indexs = shuffle_indexs[test_size:]
    train_x = x[train_indexs]
    train_y = y[train_indexs]
    test_x = x[test_indexs]
    test_y = y[test_indexs]
    return train_x, test_x, train_y, test_y


# 使用KNN算法作为分类器
def KNN(x, y):
    knn_clf = KNeighborsClassifier()
    train_x, test_x, train_y, test_y = train_test_split(x, y)  # 划分训练/测试集
    knn_clf.fit(train_x, train_y)  # 进行训练
    score = knn_clf.score(test_x, test_y)  # 实现我们的预测是100%
    print("score:", score)
    y_predict = knn_clf.predict(test_x)  # 进行预测
    matrix = confusion_matrix(test_y, y_predict)  # 生成混淆矩阵
    print(matrix)  # 打印矩阵
    return test_y, y_predict


# 实现精准率(查准率)的计算
def precision(y_true, y_predict):
    tp = TP(y_true, y_predict)
    fp = FP(y_true, y_predict)
    return tp / (tp + fp)


# 实现召回率(查全率)的计算
def recall(y_true, y_predict):
    tp = TP(y_true, y_predict)
    fn = FN(y_true, y_predict)
    return tp / (tp + fn)


x_data, y_data = get_data()
y_test, predict_y = KNN(x_data, y_data)
print("精准率(查准率): ", precision(y_test, predict_y))
print("召回率(查全率):", recall(y_test, predict_y))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kim‘s blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值