C++代码实现MATLAB中的confusionmat函数功能

发布时间:2026/10/26 10:15:15
C++代码实现MATLAB中的confusionmat函数功能 #includeiostream#includevector#includestring#includemap#includealgorithm#includestdexcept// 计算混淆矩阵// group: 真实标签// grouphat: 预测标签// order: 指定行列的顺序可选。若为空则自动使用所有出现过的唯一标签按字典序std::vectorstd::vectorintconfusionmat(conststd::vectorstd::stringgroup,conststd::vectorstd::stringgrouphat,conststd::vectorstd::stringorder{}){if(group.size()!grouphat.size()){throwstd::invalid_argument(group and grouphat must have the same number of observations.);}// 1. 确定标签顺序std::vectorstd::stringlabelsorder;if(labels.empty()){std::mapstd::string,booluniqueLabels;for(size_t i0;igroup.size();i){if(!group[i].empty())uniqueLabels[group[i]]true;if(!grouphat[i].empty())uniqueLabels[grouphat[i]]true;}for(constautopair:uniqueLabels){labels.push_back(pair.first);}}// 建立标签到索引的映射std::mapstd::string,intlabelToIdx;for(size_t i0;ilabels.size();i){labelToIdx[labels[i]]static_castint(i);}// 2. 初始化混淆矩阵labels.size() x labels.size()全 0size_t nlabels.size();std::vectorstd::vectorintC(n,std::vectorint(n,0));// 3. 填充混淆矩阵for(size_t k0;kgroup.size();k){// 跳过包含缺失值的样本用空字符串模拟 NaNif(group[k].empty()||grouphat[k].empty())continue;autoitTruelabelToIdx.find(group[k]);autoitPredlabelToIdx.find(grouphat[k]);// 标签不在指定 order 内则跳过对应行列保持 0if(itTruelabelToIdx.end()||itPredlabelToIdx.end())continue;C[itTrue-second][itPred-second];}returnC;}// 辅助函数打印混淆矩阵及标签顺序voidprintConfusionMatrix(conststd::vectorstd::vectorintC,conststd::vectorstd::stringlabels){std::coutOrder: ;for(size_t k0;klabels.size();k){if(k0)std::cout ;std::coutlabels[k];}std::cout\n;for(size_t i0;iC.size();i){for(size_t j0;jC[i].size();j){if(j0)std::cout ;std::coutC[i][j];}std::cout\n;}}intmain(){// 示例 1基本用法自动推断 orderstd::vectorstd::stringtrueLabels{1,1,2,2,3,3};std::vectorstd::stringpredLabels{1,1,2,3,4,};// 模拟 NaNautoC1confusionmat(trueLabels,predLabels);std::vectorstd::stringinferredOrder{1,2,3,4};std::cout Example 1 std::endl;printConfusionMatrix(C1,inferredOrder);// 示例 2指定 orderstd::cout\n Example 2 (specified order) std::endl;std::vectorstd::stringcustomOrder{4,3,2,1};autoC2confusionmat(trueLabels,predLabels,customOrder);printConfusionMatrix(C2,customOrder);return0;}

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询