Bird
Raised Fist0
ML Pythonml~8 mins

Handling missing values in ML Python - Model Metrics & Evaluation

Choose your learning style10 modes available
Metrics & Evaluation - Handling missing values
Which metric matters for Handling missing values and WHY

When handling missing values, the main goal is to keep the model's predictions accurate and reliable. Metrics like accuracy, precision, recall, and F1 score help us see if filling or removing missing data improves or harms the model.

Why? Because missing data can hide important patterns or create wrong ones. If we fill missing values poorly, the model might learn wrong things, lowering these metrics.

Confusion matrix example after handling missing values
      Actual \ Predicted | Positive | Negative
      -------------------|----------|---------
      Positive           |   80     |   20
      Negative           |   15     |   85
    

Here, True Positives (TP) = 80, False Negatives (FN) = 20, False Positives (FP) = 15, True Negatives (TN) = 85.

Precision = 80 / (80 + 15) = 0.842

Recall = 80 / (80 + 20) = 0.8

F1 Score = 2 * (0.842 * 0.8) / (0.842 + 0.8) ≈ 0.82

Tradeoff: Precision vs Recall when handling missing values

Filling missing values can affect precision and recall differently.

  • High precision means the model makes few false alarms. For example, in email spam detection, we want to avoid marking good emails as spam.
  • High recall means the model finds most real cases. For example, in medical diagnosis, we want to catch as many sick patients as possible.

If missing values are filled too simply (like with mean), the model might miss subtle patterns, lowering recall. If filled too aggressively, it might create false patterns, lowering precision.

Good vs Bad metric values after handling missing values

Good: Balanced precision and recall above 0.8 means the model handles missing data well and predicts reliably.

Bad: Very high accuracy but low recall (e.g., recall below 0.5) means the model misses many true cases, possibly due to poor missing value handling.

Bad: Precision very low (e.g., below 0.5) means many false alarms, possibly caused by wrong filling creating noise.

Common pitfalls in metrics when handling missing values
  • Accuracy paradox: High accuracy can be misleading if the data is imbalanced or missing values are ignored.
  • Data leakage: Using future or test data to fill missing values can inflate metrics falsely.
  • Overfitting: Filling missing values with complex methods may cause the model to memorize training data, hurting generalization.
  • Ignoring missingness: Simply dropping rows with missing values can reduce data size and bias metrics.
Self-check question

Your model has 98% accuracy but only 12% recall on the positive class after handling missing values. Is it good for production? Why or why not?

Answer: No, it is not good. The low recall means the model misses most positive cases, which can be critical depending on the task (like fraud or disease detection). High accuracy can be misleading if the positive class is rare. The missing value handling likely harmed the model's ability to find true positives.

Key Result
Handling missing values well improves balanced precision and recall, ensuring reliable model predictions.

Practice

(1/5)
1. What is the main reason to handle missing values before training a machine learning model?
easy
A. Missing values are automatically ignored by all models
B. Missing values can cause errors or reduce model accuracy
C. Missing values improve model training speed
D. Missing values increase the size of the dataset

Solution

  1. Step 1: Understand the impact of missing values

    Missing values can cause errors or confuse the model, leading to poor predictions.
  2. Step 2: Recognize model requirements

    Most machine learning models require complete data without missing values to work properly.
  3. Final Answer:

    Missing values can cause errors or reduce model accuracy -> Option B
  4. Quick Check:

    Missing values harm model accuracy = D [OK]
Hint: Missing data breaks models, so fix it first [OK]
Common Mistakes:
  • Thinking missing values speed up training
  • Assuming models ignore missing data automatically
  • Believing missing values increase dataset size
2. Which of the following is the correct way to import and use SimpleImputer from scikit-learn to fill missing values with the mean?
easy
A. from sklearn.impute import SimpleImputer\nimputer = SimpleImputer(method='mean')
B. import SimpleImputer from sklearn.impute\nimputer = SimpleImputer('mean')
C. from sklearn.imputer import SimpleImputer\nimputer = SimpleImputer(strategy=mean)
D. from sklearn.impute import SimpleImputer\nimputer = SimpleImputer(strategy='mean')

Solution

  1. Step 1: Check import syntax

    The correct import is 'from sklearn.impute import SimpleImputer'.
  2. Step 2: Check SimpleImputer initialization

    The strategy parameter must be a string like 'mean', so strategy='mean' is correct.
  3. Final Answer:

    from sklearn.impute import SimpleImputer\nimputer = SimpleImputer(strategy='mean') -> Option D
  4. Quick Check:

    Correct import and strategy syntax = A [OK]
Hint: Use strategy='mean' and correct import syntax [OK]
Common Mistakes:
  • Using 'method' instead of 'strategy'
  • Not quoting 'mean' as a string
  • Wrong import statement syntax
3. Given the following code, what will be the output of print(X_imputed)?
import numpy as np
from sklearn.impute import SimpleImputer

X = np.array([[1, 2], [np.nan, 3], [7, np.nan]])
imputer = SimpleImputer(strategy='mean')
imputer.fit(X)
X_imputed = imputer.transform(X)
print(X_imputed)
medium
A. [[1. 2.] [4. 3.] [7. 2.5]]
B. [[1. 2.] [nan 3.] [7. nan]]
C. [[1. 2.] [4. 3.] [7. nan]]
D. Error due to missing values

Solution

  1. Step 1: Calculate mean ignoring missing values

    Column 0 mean = (1 + 7) / 2 = 4; Column 1 mean = (2 + 3) / 2 = 2.5
  2. Step 2: Replace missing values with column means

    Replace np.nan in row 2, col 0 with 4; replace np.nan in row 3, col 1 with 2.5
  3. Final Answer:

    [[1. 2.] [4. 3.] [7. 2.5]] -> Option A
  4. Quick Check:

    Missing values replaced by column means = B [OK]
Hint: Mean replaces NaN with average of column values [OK]
Common Mistakes:
  • Not calculating mean correctly
  • Leaving NaNs unchanged
  • Expecting an error instead of imputation
4. Identify the error in the following code snippet for imputing missing values:
from sklearn.impute import SimpleImputer

X_train = [[1, 2], [None, 3], [7, None]]
imputer = SimpleImputer(strategy='median')
imputer.transform(X_train)
medium
A. Using null instead of np.nan causes error
B. Incorrect strategy name 'median'
C. Missing fit() call before transform()
D. SimpleImputer cannot handle 2D lists

Solution

  1. Step 1: Check method sequence

    SimpleImputer requires fit() before transform() to learn statistics from data.
  2. Step 2: Verify data and strategy

    Strategy 'median' is valid; None is accepted as missing; 2D list is acceptable.
  3. Final Answer:

    Missing fit() call before transform() -> Option C
  4. Quick Check:

    fit() must precede transform() = A [OK]
Hint: Always fit before transform with SimpleImputer [OK]
Common Mistakes:
  • Calling transform without fit
  • Confusing strategy names
  • Thinking None is invalid missing value
5. You have a training set with missing values and a test set with missing values in the same columns. What is the best practice to handle missing values before training and evaluating a model?
hard
A. Fit the imputer on training data, then transform both training and test data
B. Fit the imputer separately on training and test data
C. Fill missing values in test data with zeros, training data with mean
D. Remove all rows with missing values from both datasets

Solution

  1. Step 1: Understand data leakage risk

    Fitting imputer separately on test data leaks information from test set, causing biased evaluation.
  2. Step 2: Apply consistent imputation

    Fit imputer only on training data to learn statistics, then apply same transformation to test data.
  3. Final Answer:

    Fit the imputer on training data, then transform both training and test data -> Option A
  4. Quick Check:

    Fit on train, transform both = C [OK]
Hint: Fit imputer on train only, then transform test [OK]
Common Mistakes:
  • Fitting imputer separately on test data
  • Filling test missing values with zeros arbitrarily
  • Dropping too much data unnecessarily
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