Search code examples
pythonconfusion-matrix

Getting "index 1 is out of bounds" when try to get the False Negative in Python


I am trying to get the TP, TN, FP, and FN for my prediction

This is my code

xtrain, xval, ytrain, yval = train_test_split(df_features, df_results, test_size=0.2, random_state=9)


clf = RandomForestClassifier(n_estimators=1000, max_depth=10, random_state=0)

clf.fit(xtrain, ytrain)

y_pred = clf.predict(xval)

CM = confusion_matrix(yval, y_pred)

TN = CM[0][0]
FN = CM[1][0]
TP = CM[1][1]
FP = CM[0][1]

I get the TN value but when I try to get the FN value I get this error

CM[1][0]
Traceback (most recent call last):

  File "<ipython-input-18-4e0323bdbf74>", line 1, in <module>
    CM[1][0]

IndexError: index 1 is out of bounds for axis 0 with size 1

How can I fix that?

Edit :

print(CM)
[[19]]

this is how yval look like

yval

6     A72
46    B83
26    B88
76    A94
28    B99
38    A72
61    A72
3     B88
20    A29
45    C52
86    A75

Solution

  • Put it inside a try-catch block to avoid the error:

    try:
        Precision = cm[0][0]/(cm[0][0] + cm[1][0])
        Recall = cm[0][0]/(cm[0][0] + cm[0][1])
    except:
        pass