Search code examples
pythonconfusion-matrix

Dividing arrays in Python for confusion matrix


I have an object, 2x2, and I want to divide it by a 2x1, such that the first component divides the first row, and the second divides the second row. How can I do that?

cm = sklearn.metrics.confusion_matrix(Y1,Y2)
cm_sum = np.sum(cm, axis=1)
cm_perc = cm /  cm_sum.astype(float) * 100

Solution

  • You just need to have the right dimension. The one you are dividing has to be a column vector. We use .rehshape(-1,1) to accomplish that.

    a = np.array([[2,3], [5,6]])
    print(a)
    b = np.array([2, 4]).reshape(-1, 1)
    print(b)
    print(a/b)
    

    Output

    [[2 3]
     [5 6]]
    [[2]
     [4]]
    [[1.   1.5 ]
     [1.25 1.5 ]]
    

    So your code then will be -

    Y1 = [1,0,1,0]
    Y2 = [0,0,1,0]
    cm = metrics.confusion_matrix(Y1,Y2)
    cm_sum = np.sum(cm, axis=1).reshape(-1,1)
    cm_perc = cm / cm_sum
    

    You could also use the keepdims argument in np.sum that will basically keep the dimensions and the output will be a column vector in this case. So -

    cm_sum = np.sum(cm, axis=1, keepdims=True)
    

    will also work.