40. 日月光华 Python数据分析 - 机器学习 - 自然语言处理 模型评价-查准率/召回率

# 使用classifacation_report 函数来察看一下针对每个类别的预测准确性

from sklearn.metrics import classification_report

model = MultinomialNB(alpha=best_alpha)
model.fit(x_train_vect, y_train)
# MultinomialNB
# MultinomialNB(alpha=0.00878909090909091)

pred = model.predict(x_test_vect)
import pprint
pprint.pprint(classification_report(y_test, pred))   # 真实值/预测值
# ('              precision    recall  f1-score   support\n'
# '\n'
# '    negative       0.78      0.93      0.85      2309\n'
# '     neutral       0.65      0.38      0.48       796\n'
# '    positive       0.70      0.54      0.61       555\n'
# '\n'
# '    accuracy                           0.75      3660\n'
# '   macro avg       0.71      0.62      0.65      3660\n'
# 'weighted avg       0.74      0.75      0.73      3660\n')
# 查准率(precision)和召回率(recall):
# 比如预测是否阳性
# TP: 将正类预测为正类数
# FN: 将正类预测为负类数
# FP: 将负类预测为正类数
# TN: 将负类预测为负类数
# 查准率(precision) = TP/(TP+FP)
# 召回率(recall) = TP/(TP+FN)
# SCIKIT-LEARN 评估性能的算法都在 sklearn.metrics 包里,
# 查准率 sklearn.metrics.precison_score()
# 召回率 sklearn.metrics.recall_score()

# F1 Score 同时兼顾了分类模型的精确率和召回率。F1分数可以看作是模型精确率和召回率的一种加权平均

F1 Score = 2 * (precision * recall) / (precision + recall)
F1 = 2 * TP / (2 * TP + FP + FN)

F1计算公式的详细阐述笔记大全设计学院 (python100.com)

# 使用混淆矩阵

# 观察每种类别被错误分类的情况

# 混淆矩阵是机器学习中总结分类模型预测结果的情形分析表,以矩阵形式将数据集中的记录按照真实的类别与分类模型预测的类别判断两个标准进行汇总。其中矩阵的行表示真实值,矩阵的列表示预测值

from IPython.display import Image

image.png
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, pred)
cm
# array([[2144,  107,   34],
#       [ 405,  302,   66],
#       [ 193,   76,  333]], dtype=int64)

# 混淆矩阵的可视化
import matplotlib.pyplot as plt
%matplotlib inline
plt.matshow(cm)
plt.colorbar()
image.png

你可能感兴趣的:(40. 日月光华 Python数据分析 - 机器学习 - 自然语言处理 模型评价-查准率/召回率)