Search code examples
juliaconfusion-matrix

ConfusionMatrix table in Julia


I would like to make a confusion matrix table in Julia of classification predictions to understand the FP, TP etc. The ConfusionMatrix output of the EvalMetrics package is not the output I want. Here is some reproducible code:

julia> using EvalMetrics
julia> targets = [1,0,1,0,1,0,1]
julia> predicts = [0,0,1,1,0,1,1]

julia> ConfusionMatrix(targets, predicts)
ConfusionMatrix{Int64}(4, 3, 2, 1, 2, 2)

The output says 4 actual positives and 3 actual negatives like mentioned in docs. I don't like this output since I always have to look up what the values mean, so I prefer a table like this:

 predxact│ 0      1     
    ─────┼──────────────
       0 │     1      2
       1 │     2      2

So I was wondering if it possible to make a confusion matrix table in Julia like above?


Solution

  • Keeping the code in the OP, we can pull out the matrix entries from the confusion matrix object:

    using NamedArrays
    using EvalMetrics
    
    targets = [1,0,1,0,1,0,1]
    predicts = [0,0,1,1,0,1,1]
    
    cm = ConfusionMatrix(targets, predicts)
    
    n = NamedArray(getproperty.(Ref(cm), [:tn :fn ; :fp :tp]), 
                   (["f", "t"], ["f", "t"]), 
                   ("pred", "true"))
    

    Gives a named array which displays as follows:

    2×2 Named Matrix{Int64}
    pred ╲ true │ f  t
    ────────────┼─────
    f           │ 1  2
    t           │ 2  2