how to fix the values displayed in a confusion matrix in exponential form to normal form

Viewed 3939

While working with my project, I have obtained a confusion matrix from test data as:

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
cm

Output as:

array([[1102,   88],
   [  85,  725]], dtype=int64)

Using seaborn and matplotlib, I visualized it using the code:

import seaborn as sns
import matplotlib.pyplot as plt     

ax= plt.subplot();
sns.heatmap(cm, annot=True,cmap='Blues',ax=ax);
# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); 
ax.set_ylim(2.0, 0)
ax.set_title('Confusion Matrix');
ax.xaxis.set_ticklabels(['Fake','Real']); 
ax.yaxis.set_ticklabels(['Fake','Real']);

The output obtained is:

Confusion matrix

The problem is values with 3 digits (here 1102 been displayed as 11e+03) or above are being displayed in exponential form.

Is there a way to display it in its normal form?

4 Answers

You can use the "fmt" option:

cm = np.array([[1102,   88],[85,  725]])

import seaborn as sns
import matplotlib.pyplot as plt     

sns.heatmap(cm, annot=True,fmt="d",cmap='Blues')

enter image description here

By adding fmt="d" parameter worked.

As of 2022, I recommend using directly the following:

from sklearn.metrics import ConfusionMatrixDisplay

ConfusionMatrixDisplay.from_estimator(yourclassifier, X1_test, y1_test,values_format='d', cmap='Blues')
plt.title('Confusion matrix: Decision Tree Classifier (oversampled train set)')
plt.tick_params(axis=u'both', which=u'both',length=0)
plt.grid(b=None)
plt.show()
import matplotlib.pyplot as plt
import seaborn as sns

cm = confusion_matrix(y_test, y_pred)
cm_df = pd.DataFrame(cm,
                 index = [0, 1], 
                 columns = [0, 1])
plt.figure(figsize=(10,5))
sns.heatmap(cm_df, annot=True)
plt.title('Confusion Matrix')
plt.ylabel('Actal Values')
plt.xlabel('Predicted Values')
plt.show()

enter image description here

Related