Bird
Raised Fist0
TensorFlowml~20 mins

Confusion matrix analysis in TensorFlow - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Confusion matrix analysis
Problem:You trained a simple neural network to classify images into 3 categories. The model shows 90% training accuracy but only 75% validation accuracy. You want to understand where the model makes mistakes by analyzing the confusion matrix.
Current Metrics:Training accuracy: 90%, Validation accuracy: 75%
Issue:The validation accuracy is much lower than training accuracy, indicating possible overfitting or class confusion. You need to analyze the confusion matrix to identify which classes are confused.
Your Task
Generate and analyze the confusion matrix for the validation set predictions. Identify which classes the model confuses the most.
Use TensorFlow and Keras only.
Do not change the model architecture or training parameters.
Use the validation dataset only for confusion matrix analysis.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
TensorFlow
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from sklearn.metrics import confusion_matrix
import numpy as np
import matplotlib.pyplot as plt

# Load dataset (using MNIST for example, 3 classes: digits 0,1,2)
(x_train, y_train), (x_val, y_val) = mnist.load_data()

# Filter dataset to only classes 0,1,2 for simplicity
train_filter = np.isin(y_train, [0,1,2])
val_filter = np.isin(y_val, [0,1,2])
x_train, y_train = x_train[train_filter], y_train[train_filter]
x_val, y_val = x_val[val_filter], y_val[val_filter]

# Normalize data
x_train = x_train / 255.0
x_val = x_val / 255.0

# Build simple model
model = Sequential([
    Flatten(input_shape=(28,28)),
    Dense(64, activation='relu'),
    Dense(3, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train model
model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_val, y_val))

# Predict on validation set
val_preds_prob = model.predict(x_val)
val_preds = np.argmax(val_preds_prob, axis=1)

# Compute confusion matrix
cm = confusion_matrix(y_val, val_preds)

# Plot confusion matrix
fig, ax = plt.subplots()
cax = ax.matshow(cm, cmap='Blues')
plt.title('Confusion Matrix')
fig.colorbar(cax)
ax.set_xticks([0,1,2])
ax.set_yticks([0,1,2])
ax.set_xticklabels(['0', '1', '2'])
ax.set_yticklabels(['0', '1', '2'])
plt.xlabel('Predicted')
plt.ylabel('True')

# Show numbers in matrix
for (i, j), val in np.ndenumerate(cm):
    ax.text(j, i, val, ha='center', va='center', color='red')

plt.show()
Filtered dataset to only 3 classes for clear confusion matrix.
Trained a simple neural network on filtered data.
Predicted validation labels and computed confusion matrix using sklearn.
Visualized confusion matrix with matplotlib to identify class confusions.
Fixed axis tick label setting to avoid matplotlib warning.
Results Interpretation

Before: Only overall accuracy metrics were available (Training: 90%, Validation: 75%).

After: Confusion matrix shows detailed errors between classes 0, 1, and 2. For example, class 1 might be confused with class 2 more often.

Confusion matrix helps us see exactly which classes the model confuses. This guides targeted improvements like collecting more data for confused classes or adjusting model focus.
Bonus Experiment
Try adding class weights during training to reduce confusion between the most confused classes.
💡 Hint
Calculate class weights inversely proportional to class frequencies and pass them to model.fit() using the class_weight parameter.

Practice

(1/5)
1. What does a confusion matrix primarily show in a classification problem?
easy
A. The number of correct and incorrect predictions for each class
B. The training time of the model
C. The number of features used in the model
D. The learning rate of the optimizer

Solution

  1. Step 1: Understand the purpose of a confusion matrix

    A confusion matrix displays how many predictions were correct or wrong for each class in classification.
  2. Step 2: Compare options with the definition

    Only The number of correct and incorrect predictions for each class correctly describes this purpose; others relate to unrelated model aspects.
  3. Final Answer:

    The number of correct and incorrect predictions for each class -> Option A
  4. Quick Check:

    Confusion matrix = correct/wrong counts [OK]
Hint: Confusion matrix counts correct vs wrong predictions per class [OK]
Common Mistakes:
  • Confusing confusion matrix with training metrics like loss
  • Thinking it shows model parameters
  • Assuming it shows training time
2. Which TensorFlow function is used to compute a confusion matrix from true labels and predicted labels?
easy
A. tf.data.Dataset.from_tensor_slices()
B. tf.keras.metrics.Accuracy()
C. tf.math.confusion_matrix()
D. tf.nn.softmax()

Solution

  1. Step 1: Identify TensorFlow functions related to confusion matrix

    The function tf.math.confusion_matrix() directly computes the confusion matrix from labels.
  2. Step 2: Eliminate unrelated functions

    tf.keras.metrics.Accuracy() measures accuracy, tf.data.Dataset.from_tensor_slices() creates datasets, and tf.nn.softmax() applies softmax activation.
  3. Final Answer:

    tf.math.confusion_matrix() -> Option C
  4. Quick Check:

    Confusion matrix function = tf.math.confusion_matrix() [OK]
Hint: Use tf.math.confusion_matrix() for confusion matrix [OK]
Common Mistakes:
  • Using accuracy metric instead of confusion matrix function
  • Confusing dataset creation with confusion matrix
  • Mixing activation functions with metrics
3. Given the following code, what is the output confusion matrix?
import tensorflow as tf
true_labels = [0, 1, 2, 2, 0]
pred_labels = [0, 2, 2, 2, 0]
cm = tf.math.confusion_matrix(true_labels, pred_labels)
print(cm.numpy())
medium
A. [[2 0 0] [0 0 0] [0 1 2]]
B. [[2 0 0] [0 1 0] [0 0 2]]
C. [[1 0 1] [0 0 1] [0 0 2]]
D. [[2 0 0] [0 0 1] [0 0 2]]

Solution

  1. Step 1: Count true vs predicted labels for each class

    Class 0 true: predicted 0 twice; class 1 true: predicted 2 once; class 2 true: predicted 2 twice.
  2. Step 2: Build confusion matrix rows

    Row 0: [2 correct (0 predicted as 0), 0 predicted as 1, 0 predicted as 2]; Row 1: [0, 0, 1]; Row 2: [0, 0, 2].
  3. Final Answer:

    [[2 0 0] [0 0 1] [0 0 2]] -> Option D
  4. Quick Check:

    Count matches matrix entries [OK]
Hint: Count true vs predicted labels per class to fill matrix [OK]
Common Mistakes:
  • Mixing up rows and columns in the matrix
  • Counting predicted labels instead of true labels
  • Forgetting to count all instances
4. Identify the error in this TensorFlow code snippet for confusion matrix calculation:
import tensorflow as tf
true = [0, 1, 1, 0]
pred = [0, 1, 0]
cm = tf.math.confusion_matrix(true, pred)
print(cm)
medium
A. The confusion matrix function is misspelled
B. The true and predicted label lists have different lengths
C. TensorFlow is not imported correctly
D. The print statement is missing parentheses

Solution

  1. Step 1: Check input list lengths

    True labels list has 4 elements; predicted labels list has 3 elements, causing mismatch.
  2. Step 2: Understand function requirements

    tf.math.confusion_matrix() requires true and predicted labels to be same length to compare element-wise.
  3. Final Answer:

    The true and predicted label lists have different lengths -> Option B
  4. Quick Check:

    Input lengths must match [OK]
Hint: Ensure true and predicted label lists have same length [OK]
Common Mistakes:
  • Ignoring length mismatch error
  • Assuming function name typo
  • Thinking print syntax is wrong in Python 3
5. You have a 3-class classification problem with classes 0, 1, and 2. After training, your confusion matrix is:
[[50  2  3]
 [ 4 45  1]
 [ 5  2 40]]
Which class has the highest precision, and how do you calculate it from the matrix?
hard
A. Class 1; precision = TP / (TP + FP) = 45 / (45 + 4 + 1)
B. Class 2; precision = TP / (TP + FP) = 40 / (3 + 1 + 40)
C. Class 0; precision = TP / (TP + FP) = 50 / (50 + 4 + 5)
D. Class 1; precision = TP / (TP + FP) = 45 / (2 + 45 + 2)

Solution

  1. Step 1: Understand precision calculation

    Precision for a class = True Positives (TP) / (TP + False Positives (FP)). TP is diagonal element; FP is sum of column excluding TP.
  2. Step 2: Calculate precision for each class

    Class 0: TP=50; FP=sum column 0 excluding TP=4+5=9; precision=50/(50+9)=50/59≈0.847. Class 1: TP=45; FP=2+2=4; precision=45/(45+4)=45/49≈0.918. Class 2: TP=40; FP=3+1=4; precision=40/(40+4)=40/44≈0.909.
  3. Step 3: Identify highest precision

    Class 1 has the highest precision (≈0.918).
  4. Final Answer:

    Class 1; precision = TP / (TP + FP) = 45 / (45 + 4 + 1) -> Option A
  5. Quick Check:

    Precision = TP / (TP + FP) [OK]
Hint: Precision = TP / (TP + FP) using confusion matrix columns [OK]
Common Mistakes:
  • Confusing precision with recall
  • Using row sums instead of column sums for FP
  • Mixing up TP and FP positions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard