python confusion matrix 混淆矩阵
【2】 混淆矩阵-百度百科
【3】 Python中生成并绘制混淆矩阵(confusion matrix)
【4】 使用python绘制混淆矩阵(confusion_matrix)
示例:
Python画混淆矩阵程序示例,摘自【4】。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt import numpy as np def plot_confusion_matrix(cm, labels, title = 'Confusion Matrix' ): plt.imshow(cm, interpolation = 'nearest' , cmap = 'Blues' ) plt.title(title) plt.colorbar() xlocations = np.array( range ( len (labels))) plt.xticks(xlocations, labels, rotation = 90 ) plt.yticks(xlocations, labels) plt.ylabel( 'True label' ) plt.xlabel( 'Predicted label' ) label = [ "ant" , "bird" , "cat" ] tick_marks = np.array( range ( len (label))) + 0.5 y_true = [ 2 , 0 , 2 , 2 , 0 , 1 ] y_pred = [ 0 , 0 , 2 , 2 , 0 , 2 ] cm = confusion_matrix(y_true, y_pred) np.set_printoptions(precision = 2 ) cm_normalized = cm.astype( 'float' ) / cm. sum (axis = 1 )[:, np.newaxis] print (cm_normalized) plt.figure(figsize = ( 12 , 8 ), dpi = 120 ) ind_array = np.arange( len (label)) x, y = np.meshgrid(ind_array, ind_array) for x_val, y_val in zip (x.flatten(), y.flatten()): c = cm_normalized[y_val][x_val] if c > 0.0 : plt.text(x_val, y_val, "%0.2f" % (c,), color = 'red' , fontsize = 17 , va = 'center' , ha = 'center' ) # offset the tick plt.gca().set_xticks(tick_marks, minor = True ) plt.gca().set_yticks(tick_marks, minor = True ) plt.gca().xaxis.set_ticks_position( 'none' ) plt.gca().yaxis.set_ticks_position( 'none' ) plt.grid( True , which = 'minor' , linestyle = '-' ) plt.gcf().subplots_adjust(bottom = 0.15 ) plot_confusion_matrix(cm_normalized, label, title = 'Normalized confusion matrix' ) # plt.savefig('../Data/confusion_matrix.png', format='png') plt.show() |
运行结果:
分类:
Python
, Deep Learning
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通