'How to convert Confusion matrix to Normalized confusion matrix?

i used this code to gey accuracy , and i got normal confusion matrix . but don't know how to normalize this confision matrix. how to use normalize in seaborn?

# Generate predictions
model.load_weights('tl_model_paperb6fin.weights.best.hdf5') # initialize the best trained weights
true_classes = validgen.classes
class_indices = traingen.class_indices
class_indices = dict((v,k) for k,v in class_indices.items())
B3_preds = model.predict(validgen)
B3_pred_classes = np.argmax(B3_preds, axis=1)

from sklearn.metrics import accuracy_score
B3_acc = accuracy_score(true_classes, B3_pred_classes)
print("B3 Model Accuracy with Fine-Tuning: {:.2f}%".format(B3_acc * 100))

#%matplotlib ipympl
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix

class_names = ['Container Ship','Bulk Carrier','Passengers Ship', 'Ro-ro/passenger Ship','Ro-ro Cargo', 
               'Tug','Vehicles Carrier','Reefer','Yacht','Sailing Vessel',
        'Heavy Load Carrier','Wood Chips Carrier','Livestock Carrier','Fire Fighting Vessel','Patrol Vessel', 
        'Platform','Standby Safety Vessel','Combat Vessel','Training Ship','Icebreaker', 
        'Replenishment Vessel','Tankers','Fishing Vessels','Supply Vessels','Carrier/Floating', 
        'Dredgers']

def plot_heatmap(y_true, y_pred, class_names, ax, title,  normalize=True):
    cm = confusion_matrix(y_true, y_pred)
    sns.heatmap(
        cm, 
        annot=True, 
        square=True, 
        xticklabels=class_names, 
        yticklabels=class_names,
        fmt='d', 
        cmap=plt.cm.Blues,
        cbar=False,
        ax=ax
    )
    ax.set_title(title, fontsize=12)
    ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha="right",fontsize=20)
    ax.set_yticklabels(ax.get_yticklabels(),fontsize=20)
    ax.set_ylabel('True Label', fontsize=30)
    ax.set_xlabel('Predicted Label', fontsize=30)

fig, (ax) = plt.subplots(1, 1, figsize=(40, 20))

#plot_heatmap(true_classes, scratch_pred_classes, class_names, ax1, title="Custom CNN")    
plot_heatmap(true_classes, B3_pred_classes, class_names, ax, title="Transfer Learning (B5)  Fine-Tuning")    
#plot_heatmap(true_classes, vgg_pred_classes_ft, class_names, ax3, title="Transfer Learning (VGG16) with Fine-Tuning")    

fig.suptitle("", fontsize=1)
fig.tight_layout()
fig.subplots_adjust(top=1.25)
plt.show()

i got notrmal confusion matrix

but don't know how to normalize confusion matrix , as no normalize in seaborn



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source