【实践】数据挖掘DM课程课业打卡实验3 分类器性能度量
叮嘟!这里是小啊呜的学习课程资料整理。好记性不如烂笔头,今天也是努力进步的一天。一起加油进阶吧!
一、实验目的
(1)理解分类器性能度量的方法。
(2)编程ROC曲线绘制。
二、实验内容
1、编程实现ROC曲线绘制的函数roc_plot。
其中,分类概率使用matlab自带的朴素贝叶斯函数得到。
测试代码如下:
load('testingData.mat')
load('trainingData.mat')
nb = NaiveBayes.fit(trAttr, trLabels);
p=posterior (nb,tstAttr);
y1=p(:,2);
[auc1 ,FPR1 ,TPR1 ] = roc_plot(y1,tstLabels);
(将执行正确的roc_plot函数代码粘贴在此处,核心代码要求有注释)
% load('testingData.mat')
% load('trainingData.mat')
% nb = NaiveBayes.fit(trAttr, trLabels);
% p=posterior (nb,tstAttr);
% y1=p(:,2);
% [auc1 ,FPR1 ,TPR1 ] = roc_plot(y1,tstLabels);
function [AUC,FPR,TPR] = roc_plot(deci,label_y)
[val,ind]=sort(deci);
roc_y=label_y(ind);
Num=length(roc_y);
FPR=zeros(Num,1);
TPR=zeros(Num,1);
for i=1:Num
TP=sum(roc_y(i:end)==1);
FP=sum(roc_y(i:end)==0);
P=sum(roc_y(:)==1);
N=sum(roc_y(:)==0);
TPR(i)=TP/P;
FPR(i)=FP/N;
end
TPR=[TPR;0];
FPR=[FPR;0];
AUC=0;
for i=2:Num+1
AUC=AUC+TPR(i)*(FPR(i-1)-FPR(i));
end
figure,plot(FPR,TPR);
xlabel('False Positive Rate');
ylabel('True Positive Rate');
title(['ROC curve (AUC = ' num2str(AUC) ')']);
end
2、(难度2)编程实现ROC曲线绘制的函数roc_plot。
其中,分类概率使用自己编写的朴素贝叶斯函数bys_post1得到。
测试代码如下:
load('testingData.mat')
load('trainingData.mat')
[post4all]=bys_post1(trAttr, trLabels,tstAttr);
y2=post4all(:,1);
[auc2 ,FPR2 ,TPR2 ] = roc_plot(y2,tstLabels);
(将执行正确的bys_post1函数代码粘贴在此处,核心代码要求有注释)
function [Params,prior,AllLabels] = NaiveBayesTrain1(trAttr, trLabels)
%NaiveBayesTrain只处理连续分类,不处理分类属性;
AllLabels = unique(trLabels);
numClass = length(AllLabels); %取得所有类标号的种类个数;
for i =1:numClass
ind=find(trLabels==AllLabels(i));
Ind4Class{i,1}=ind;
prior(i)=length(ind)/length(trLabels);
end
numAttr=size(trAttr,2);
Params{numClass,numAttr}=[];%初始化参数cell;
for AttrInd =1:numAttr
AttrVals=trAttr(:,AttrInd);
for i=1:numClass
Params{i,AttrInd}=GetParams4ContiAttr(AttrVals,Ind4Class{i,1});
end
end
end
function Params1=GetParams4ContiAttr(AttrVals,ind)
AttrVals4ThisClass=AttrVals(ind);
Params1(1)=mean(AttrVals4ThisClass); %求得均值;
Params1(2)=var(AttrVals4ThisClass); %求得方差;
end
function post=NaiveBayesPredict1(Params,prior,tstAttr)%%分类
numClass=length(prior); %取得类标号种类个数
numAttr=length(tstAttr);
post=[];
for i=1;numClass
p_AttrCond=1;
for AttrInd=1;numAttr
AttrVals=tstAttr(AttrInd);
mean=Params{i,AttrInd}(1);
varriance=Params{i,AttrInd}(2);
sig=sqrt(varriance);
p=(1/(sqrt(2*pi)*sig))*exp(-(AttrVals-mean)^2/(2*sig^2));
p_AttrCond=p_AttrCond*p;
end
post(i)=p_AttrCond*prior(i);
end
end
Ending!
更多课程知识学习记录随后再来吧!
就酱,嘎啦!
注:
人生在勤,不索何获。