public String confusionMatrix ( ) { int nClasses = numClasses ( ) ; if ( confusion == null ) { return "Confusion matrix: <no data>" ; } //First: work out the maximum count List < Integer > classes = confusion . getClasses ( ) ; int maxCount = 1 ; for ( Integer i : classes ) { for ( Integer j : classes ) { int count = confusion ( ) . getCount ( i , j ) ; maxCount = Math . max ( maxCount , count ) ; } } maxCount = Math . max ( maxCount , nClasses ) ; //Include this as header might be bigger than actual values int numDigits = ( int ) Math . ceil ( Math . log10 ( maxCount ) ) ; if ( numDigits < 1 ) numDigits = 1 ; String digitFormat = "%" + ( numDigits + 1 ) + "d" ; StringBuilder sb = new StringBuilder ( ) ; //Build header: for ( int i = 0 ; i < nClasses ; i ++ ) { sb . append ( String . format ( digitFormat , i ) ) ; } sb . append ( "\n" ) ; int numDividerChars = ( numDigits + 1 ) * nClasses + 1 ; for ( int i = 0 ; i < numDividerChars ; i ++ ) { sb . append ( "-" ) ; } sb . append ( "\n" ) ; //Build each row: for ( int actual = 0 ; actual < nClasses ; actual ++ ) { String actualName = resolveLabelForClass ( actual ) ; for ( int predicted = 0 ; predicted < nClasses ; predicted ++ ) { int count = confusion . getCount ( actual , predicted ) ; sb . append ( String . format ( digitFormat , count ) ) ; } sb . append ( " | " ) . append ( actual ) . append ( " = " ) . append ( actualName ) . append ( "\n" ) ; } sb . append ( "\nConfusion matrix format: Actual (rowClass) predicted as (columnClass) N times" ) ; return sb . toString ( ) ; }
Get the confusion matrix as a String