0

Sorry if this is a bit silly I am new to coding. I tried creating a confusion matrix, I used the unique function and then created a null matrix and tried adding loop counters to be able to determine time-complexity but it returns 0. I think it is because I did not call the function correctly but I do not know how to do it. Thank you so much for your help.

L = 0
def confusionmatrix(target, prediction):
    dataframe=creatematrixnull(target)    
    for i in range(len(target)):
        dataframe[target[i]][prediction[i]]+=1
        L=L+1
        
    return dataframe
print(L)
ariel
  • 1
  • 1
    you forgot to ask a question – jsotola Feb 21 '22 at 19:00
  • If the output is 0 then that's because *len(target) == 0* or if *confusionmatrix()* was never called – DarkKnight Feb 21 '22 at 19:02
  • OP isn't actually talking about the return value, they're talking about the value of `L` after calling the function (which will always be `0` because that's what it was set to in the outer scope). – Samwise Feb 21 '22 at 19:21

1 Answers1

0

When you assign a new value to L inside your function, you're actually creating a new variable that's independent of the L outside the function (which never changes and stays zero). If you want to be able to access this value outside of the function, return it:

def confusionmatrix(target, prediction):
    L = 0
    dataframe=creatematrixnull(target)    
    for i in range(len(target)):
        dataframe[target[i]][prediction[i]]+=1
        L=L+1
    return dataframe, L

df, L = confusionmatrix(target, prediction)  # you need to actually call the function!
print(L)

However, you don't actually need to return L in this case, because it will always be the same as len(target). The easier way to write this function and get L afterward is:

def confusionmatrix(target, prediction):
    dataframe = creatematrixnull(target)    
    for t, p in zip(target, prediction):
        dataframe[t][p] += 1
    return dataframe

df = confusionmatrix(target, prediction)
L = len(target)
print(L)

Note that iterating over t, p in zip(target, prediction) gives you the same values as you'd get from target[i] and prediction[i] (as t and p) that you'd get by iterating over i in range(len(target)).

Samwise
  • 68,105
  • 3
  • 30
  • 44