复习: 实现精准率和召回率

精准率:预测有100个人有癌症,在这些预测中,有多少是准确的。 \(precision = \frac{TP}{TP + FP}\)

  • 需要的是精确度

召回率:实际上100人有癌症,我们的预测算法能从中正确的挑出多少。 \(recall = \frac{TP}{P} = \frac{TP}{TP + FN}\)

  • 需要的是预测的范围,预测的多不多
  • 在scikit-learn中的混淆矩阵;精准率和召回率
# 混淆矩阵
from sklearn.metrics import confusion_matrix
confusion_matrix(y_test, y_log_predict)

# 精确率
from sklearn.metrics import precision_score
precision_score(y_test, y_log_predict)

from sklearn.metrics import recall_score
recall_score(y_test, y_log_predict)
  • 自己手写
import numpy as np
from sklearn import datasets

# 导入数据
digits = datasets.load_digits()        # 手写数字识别
X = digits.data
y = digits.target.copy()     # 深拷贝
# print(X)
# print(y)

y[digits.target==9] = 1      # 等于9的,  为1
y[digits.target!=9] = 0      # 不等于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)
print(log_reg.score(X_test, y_test))      # 这是准确度 

# 注意,此数据为 偏斜较大的数据,因此,需要考察其他指标
# 逻辑回归的预测值
y_log_predict = log_reg.predict(X_test)

# 对于混淆矩阵
# TN
def TN(y_true, y_predict):
    assert len(y_true) == len(y_predict)
    return np.sum((y_true == 0) & (y_predict == 0))    # 预测为0,预测正确,y_true为 0

# TN 值
print(TN(y_test, y_log_predict))

# FP
def FP(y_true, y_predict):
    assert len(y_true) == len(y_predict)
    return np.sum((y_true == 0) & (y_predict == 1))    # 预测为9,预测错误,y_true为 0

print(FP(y_test, y_log_predict))


def FN(y_true, y_predict):
    assert len(y_true) == len(y_predict)
    return np.sum((y_true == 1) & (y_predict == 0))   # 预测成0,预测错误,y_true为 1

print(FN(y_test, y_log_predict))


def TP(y_true, y_predict):
    assert len(y_true) == len(y_predict)
    return np.sum((y_true == 1) & (y_predict == 1))   # 预测成 9,预测正确,y_true为 1

print(TP(y_test, y_log_predict))


def confusion_matrix(y_true, y_predict):
    return np.array([
                     [TP(y_true, y_predict), FN(y_true, y_predict)],
                     [FP(y_true, y_predict), TN(y_true, y_predict)]
                    ])

confusion_matrix(y_test, y_log_predict)

# precision
def precision_score(y_true, y_predict):
    tp = TP(y_true, y_predict)
    fp = FP(y_true, y_predict)
    try:
        return tp / (tp + fp)
    except:
        return 0.0
    
print("精准率: ", precision_score(y_test, y_log_predict))


# recall
def recall_score(y_true, y_predict):
    tp = TP(y_true, y_predict)
    fn = FN(y_true, y_predict)
    try:
        return tp / (tp + fn)
    except:
        return 0.0
    
print("召回率:", recall_score(y_test, y_log_predict))
0.9755555555555555
403
2
9
36
[[ 36   9]
 [  2 403]]
精准率:  0.9473684210526315
召回率: 0.8
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章