1

I am trying to find the indices of the misclassified samples using the following code. But I found that the append function does not actually append the index. Can anyone explain why is this happening?

for i in range(len(predictions)):
    misclassified_indices = []
    if y_test[i] != predictions[i]:
        print(i)
        misclassified_indices.append(i)
        
print(misclassified_indices)
19
357
1553     # All misclassified samples are printed correctly ...
[]       # ... but it does not append to this list

3 Answers 3

4

Because you reset the misclassified_indices to [] inside the loop. Just move your second line to outside of the loop.

3

try to put the list outside of the loop:

misclassified_indices = [] # <-- goes here
for i in range(len(predictions)):
    
    if y_test[i] != predictions[i]:
        print(i)
        misclassified_indices.append(i)
        
print(misclassified_indices)
2

You should initially assign your list outside the loop:

misclassified_indices = []
for i in range(len(predictions)):

In your original code, misclassified_indices is reassigned back to an empty list on every loop iteration, which causes it to be empty at the end.

You can also shorten your code using list comprehension:

misclassified_indices = [i for i in range(len(predictions)) if y_test[i] != predictions[i]]

Not the answer you're looking for? Browse other questions tagged or ask your own question.