Bird
Raised Fist0

Implement Confusion Matrix from Predictions

CODINGbeginnerInterview freq: very_high
Choose your preparation mode6 modes available
▶
Execution Trace
Step 1/6
Initialize matrix

Confusion matrix initialized to zeros for 3 classes.

🎯 Understanding the initial setup of the confusion matrix is crucial.
import numpy as np
conf_matrix = np.zeros((3, 3), dtype=int)
First prediction

First prediction is class 0, actual is class 0. Increment TP.

🎯 Correctly identifying true positives is important for accuracy.
predictions = [0, 1, 2, 1, 0]
actuals = [0, 1, 2, 0, 1]
conf_matrix[actuals[0], predictions[0]] += 1
Second prediction

Second prediction is class 1, actual is class 1. Increment TP.

🎯 True positives are key for precision and recall metrics.
conf_matrix[actuals[1], predictions[1]] += 1
Third prediction

Third prediction is class 2, actual is class 2. Increment TP.

🎯 Correctly identifying true positives is crucial for model evaluation.
conf_matrix[actuals[2], predictions[2]] += 1
Fourth prediction

Fourth prediction is class 1, actual is class 0. Increment FN.

🎯 False negatives can lead to underestimation of model performance.
conf_matrix[actuals[3], predictions[3]] += 1
Fifth prediction

Fifth prediction is class 0, actual is class 1. Increment FP.

🎯 False positives are critical for understanding precision.
conf_matrix[actuals[4], predictions[4]] += 1
📊
Diagram
Diagram
┌──────────────────────────────────────────────────────────────┐
│                      Confusion Matrix                        │
├───────────────┬───────────────┬───────────────┬───────────────┤
│               │ Predicted: 0 │ Predicted: 1  │ Predicted: 2  │
├───────────────┼───────────────┼───────────────┼───────────────┤
│ Actual: 0     │      TN       │      FP       │      FP       │
├───────────────┼───────────────┼───────────────┼───────────────┤
│ Actual: 1     │      FN       │      TP       │      FN       │
├───────────────┼───────────────┼───────────────┼───────────────┤
│ Actual: 2     │      FN       │      FN       │      TP       │
└───────────────┴───────────────┴───────────────┴───────────────┘
  • Confusion Matrix: A table layout that allows visualization of the performance of an algorithm.
  • Predicted: Columns represent the predicted classes.
  • Actual: Rows represent the actual classes.
🔑
Key Moments
▲
Q: Why is it important to initialize the confusion matrix with zeros?
A: Initializing with zeros ensures that the matrix starts with no bias and accurately reflects the counts of predictions as they are processed.
Q: How does the confusion matrix help in evaluating model performance?
A: It provides a detailed breakdown of true positives, false positives, true negatives, and false negatives, which are essential for calculating precision, recall, and accuracy.
Q: What is the impact of false positives on model evaluation?
A: False positives can lead to an overestimation of the model's performance, particularly affecting precision.

This visual trace document explains how to implement a confusion matrix from prediction and true label arrays. The ASCII diagram illustrates a 3x3 confusion matrix for a multi-class classification problem, showing the relationships between predicted and actual classes. The step-by-step trace walks through the process of updating the matrix with predictions, highlighting the importance of true positives, false positives, true negatives, and false negatives in evaluating model performance. Key moments focus on understanding the initialization, evaluation metrics, and the impact of false positives.

Primary Focus

✓ Building a confusion matrix from prediction and true label arrays.

Practice

(1/5)
1.
import numpy as np

def convolve2d(image, kernel):
    kernel_height, kernel_width = kernel.shape
    image_height, image_width = image.shape
    output_height = image_height - kernel_height + 1
    output_width = image_width - kernel_width + 1
    output = np.zeros((output_height, output_width))
    for i in range(output_height):
        for j in range(output_width):
            output[i, j] = np.sum(image[i:i+kernel_height, j:j+kernel_width] * kernel)
    return output

image = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
kernel = np.array([[1, 0], [0, -1]])
print(convolve2d(image, kernel))
easy
A. array([[ 0., 1.], [ 1., 0.]])
B. array([[ 0., 1.], [ 1., 2.]])
C. array([[ 0., 1.], [ 1., 1.]])
D. array([[ 0., 1.], [ 1., -1.]])

Solution

  1. Step 1: Understand the convolution operation

    The function performs a 2D convolution by sliding the kernel over the image and computing the sum of element-wise products.
  2. Step 2: Calculate the output

    For each position, calculate the sum of products:
    Top-left: (1*1 + 2*0 + 4*0 + 5*-1) = 0
    Top-right: (2*1 + 3*0 + 5*0 + 6*-1) = 1
    Bottom-left: (4*1 + 5*0 + 7*0 + 8*-1) = 1
    Bottom-right: (5*1 + 6*0 + 8*0 + 9*-1) = -1
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Sum of element-wise products for each position. [OK]
Hint: Sum of element-wise products for each position. [OK]
Common Mistakes:
2. What does the following Python code snippet output when implementing linear regression using gradient descent?
import numpy as np

X = np.array([[1, 2], [3, 4], [5, 6]])
y = np.array([1, 2, 3])
weights = np.zeros(X.shape[1])
learning_rate = 0.01

for _ in range(1):
    predictions = X.dot(weights)
    errors = predictions - y
    gradient = X.T.dot(errors) / len(y)
    weights -= learning_rate * gradient

print(weights)
easy
A. [0.01, 0.02]
B. [0.1, 0.2]
C. [0.03, 0.04]
D. [0.05, 0.06]

Solution

  1. Step 1: Calculate initial predictions and errors

    Initial predictions are [0, 0, 0] since weights are zeros. Errors are [-1, -2, -3].
  2. Step 2: Compute gradient and update weights

    Gradient is [-3, -6]. Updated weights are [0.01, 0.02].
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Initial weights zero, single update step. [OK]
Hint: Initial weights zero, single update step. [OK]
Common Mistakes:
3.
import numpy as np

def euclidean_distance(a, b):
    return np.sqrt(np.sum((a - b) ** 2))

vector1 = np.array([1, 2, 3])
vector2 = np.array([4, 5])

result = euclidean_distance(vector1, vector2)
print(result)
medium
A. Returns NaN due to broadcasting
B. Throws a ValueError due to shape mismatch
C. Returns 0.0
D. Returns a large number due to incorrect subtraction

Solution

  1. Step 1: Check vector shapes

    vector1 has shape (3,), vector2 has shape (2,).
  2. Step 2: Identify operation failure

    Subtraction fails due to shape mismatch, raising a ValueError.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Shape mismatch leads to ValueError. [OK]
Hint: Shape mismatch leads to ValueError. [OK]
Common Mistakes:
4. In a pipeline that includes flipping, cropping, and normalizing images, where should normalization be applied for best results?
medium
A. Before flipping and cropping
B. After flipping but before cropping
C. After cropping but before flipping
D. After both flipping and cropping

Solution

  1. Step 1: Understand the impact of operations

    Normalization should be the last step to ensure consistent scaling.
  2. Step 2: Evaluate each option

    Applying normalization last ensures it accounts for all transformations.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Normalize last for consistent scaling. [OK]
Hint: Normalize last for consistent scaling. [OK]
Common Mistakes:
5. In a multi-class classification problem, how would you modify the softmax function to handle very large input values?
medium
A. Subtract the maximum input value before applying softmax.
B. Subtract the mean of the input values before applying softmax.
C. Use a sigmoid function instead of softmax.
D. Apply a logarithmic transformation to the inputs before softmax.

Solution

  1. Step 1: Address numerical stability

    Subtracting the max input value prevents overflow in exponentials.
  2. Step 2: Ensure correct probabilities

    This adjustment maintains the relative differences between inputs.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Subtract max for stability in softmax [OK]
Hint: Subtract max for stability in softmax [OK]
Common Mistakes:
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