import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
# Assume model, X_val, y_val are predefined
# For demonstration, create dummy data and model predictions
num_classes = 3
# Dummy true labels for validation set
y_true = np.array([0, 1, 2, 2, 1, 0, 1, 2, 0, 1])
# Dummy predicted labels from model
y_pred = np.array([0, 2, 2, 2, 1, 0, 0, 2, 0, 1])
# Compute confusion matrix
cm = tf.math.confusion_matrix(y_true, y_pred, num_classes=num_classes).numpy()
# Normalize confusion matrix by true label counts
cm_norm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
# Plot confusion matrix
plt.figure(figsize=(6, 6))
plt.imshow(cm_norm, interpolation='nearest', cmap=plt.cm.Blues)
plt.title('Normalized Confusion Matrix')
plt.colorbar()
classes = [f'Class {i}' for i in range(num_classes)]
plt.xticks(np.arange(num_classes), classes, rotation=45)
plt.yticks(np.arange(num_classes), classes)
# Loop over data dimensions and create text annotations.
thresh = cm_norm.max() / 2.
for i in range(num_classes):
for j in range(num_classes):
plt.text(j, i, f'{cm[i, j]} ({cm_norm[i, j]:.2f})',
horizontalalignment='center',
color='white' if cm_norm[i, j] > thresh else 'black')
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.tight_layout()
plt.show()