Tuesday, June 7, 2011

receiver operating characteristic (roc) and area under the curve (AUC) in matlab

Here is an implementation corresponding to Tom Fawcett's algorithm 3 in "roc graphs: notes and practical considerations for researchers, " 2004.

function auc=areaundercurve(FPR,TPR);
% given true positive rate and false positive rate calculates the area under the curve
% true positive are on the y-axis and false positives on the x-axis
% sum rectangular area between all points
% example: auc=areaundercurve(FPR,TPR);
[x2,inds]=sort(FPR);
x2=[x2,1]; % the trick is in inventing a last point 1,1
y2=TPR(inds);
y2=[y2,1];
xdiff=diff(x2);
xdiff=[x2(1),xdiff];
auc1=sum(y2.*xdiff); % upper point area
auc2=sum([0,y2([1:end-1])].*xdiff); % lower point area
auc=mean([auc1,auc2]);


function [TP,FP]=getfptp(T,Y)
Y(Y>=0)=1;Y(Y<0)=-1; % target class (positive) is 1
TP=sum( ( (Y==1) + (T==1) )==2 );
FN=sum( ( (Y==-1) + (T==1) )==2 );
FP=sum( ( (Y==1) + (T==-1) )==2 );
TN=sum( ( (Y==-1) + (T==-1) )==2 );
TP=TP/(TP+FN);
FP=FP/(FP+TN);
end

No comments: