Bird
Raised Fist0
ML Pythonml~20 mins

Handling missing values in ML Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Missing Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why is it important to handle missing values before training a machine learning model?

Choose the best reason why missing values must be handled before training a model.

AMissing values always improve model accuracy by adding randomness.
BMissing values can cause errors or unexpected behavior in many machine learning algorithms.
CModels automatically ignore missing values, so handling them is optional.
DMissing values reduce the size of the dataset, which speeds up training.
Attempts:
2 left
💡 Hint

Think about what happens if the model sees empty or unknown data points.

❓ Predict Output
intermediate
2:00remaining
What is the output of this code that fills missing values with the column mean?

Given the following code, what will be the resulting DataFrame?

ML Python
import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [1, np.nan, 3], 'B': [4, 5, np.nan]})
df_filled = df.fillna(df.mean())
print(df_filled)
A
     A    B
0  1.0  4.0
1  2.0  5.0
2  3.0  4.5
B
     A    B
0  1.0  4.0
1  NaN  5.0
2  3.0  NaN
C
     A    B
0  1.0  4.0
1  2.0  NaN
2  3.0  4.5
D
     A    B
0  1.0  4.0
1  3.0  5.0
2  3.0  4.5
Attempts:
2 left
💡 Hint

Calculate the mean of each column ignoring NaNs, then replace NaNs with those means.

❓ Model Choice
advanced
2:00remaining
Which model type is most robust to missing values without imputation?

Choose the model that can handle missing values internally without needing to fill them first.

ADecision Trees
BLinear Regression
CK-Nearest Neighbors
DSupport Vector Machines
Attempts:
2 left
💡 Hint

Think about models that split data based on feature values and can branch around missing data.

❓ Metrics
advanced
2:00remaining
How does improper handling of missing values affect model evaluation metrics?

What is the most likely effect on accuracy if missing values are dropped from the test set but not from the training set?

AAccuracy will be unaffected because missing values are only in training data.
BAccuracy will be artificially low because the model sees fewer test samples.
CAccuracy will be exactly the same as if missing values were imputed.
DAccuracy will be artificially high because the test set is cleaner than training data.
Attempts:
2 left
💡 Hint

Consider how removing test samples with missing data changes the difficulty of the test set.

🔧 Debug
expert
2:00remaining
What error does this code raise when imputing missing values with scikit-learn's SimpleImputer?

Examine the code below and select the error it produces when run.

ML Python
from sklearn.impute import SimpleImputer
import numpy as np

X = np.array([[1, 2], [np.nan, 3], [7, 6]])
imputer = SimpleImputer(strategy='median')
X_imputed = imputer.fit_transform(X)
print(X_imputed)
AValueError: Cannot use median strategy with non-numeric data
BTypeError: 'SimpleImputer' object is not callable
C
No error; output is [[1. 2.]
 [4. 3.]
 [7. 6.]]
DAttributeError: 'numpy.ndarray' object has no attribute 'fit_transform'
Attempts:
2 left
💡 Hint

Check if the input array is numeric and if the median strategy is valid.

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