Missing values can cause errors or wrong results in machine learning. Handling them helps models learn better and make good predictions.
Handling missing values in ML Python
from sklearn.impute import SimpleImputer imputer = SimpleImputer(strategy='mean') X_imputed = imputer.fit_transform(X)
SimpleImputer replaces missing values with a chosen strategy like mean, median, or most frequent value.
You must fit the imputer on training data, then transform both training and test data.
imputer = SimpleImputer(strategy='mean')
X_imputed = imputer.fit_transform(X)imputer = SimpleImputer(strategy='median')
X_imputed = imputer.fit_transform(X)imputer = SimpleImputer(strategy='most_frequent')
X_imputed = imputer.fit_transform(X)imputer = SimpleImputer(strategy='constant', fill_value=0) X_imputed = imputer.fit_transform(X)
This program shows how to replace missing values with the mean of each column using SimpleImputer.
import numpy as np from sklearn.impute import SimpleImputer # Sample data with missing values (np.nan) X = np.array([[1, 2], [np.nan, 3], [7, np.nan], [np.nan, np.nan]]) # Create imputer to fill missing values with mean imputer = SimpleImputer(strategy='mean') # Fit imputer on data and transform X_imputed = imputer.fit_transform(X) print("Original data:\n", X) print("\nData after imputing missing values with mean:\n", X_imputed)
Always fit the imputer only on training data to avoid data leakage.
Imputation strategies depend on the data type and distribution.
For categorical data, use 'most_frequent' or 'constant' strategies.
Missing values can cause problems in machine learning models.
SimpleImputer helps fill missing values with mean, median, or other strategies.
Always fit on training data and transform both training and test sets.
Practice
Solution
Step 1: Understand the impact of missing values
Missing values can cause errors or confuse the model, leading to poor predictions.Step 2: Recognize model requirements
Most machine learning models require complete data without missing values to work properly.Final Answer:
Missing values can cause errors or reduce model accuracy -> Option BQuick Check:
Missing values harm model accuracy = D [OK]
- Thinking missing values speed up training
- Assuming models ignore missing data automatically
- Believing missing values increase dataset size
Solution
Step 1: Check import syntax
The correct import is 'from sklearn.impute import SimpleImputer'.Step 2: Check SimpleImputer initialization
The strategy parameter must be a string like 'mean', so strategy='mean' is correct.Final Answer:
from sklearn.impute import SimpleImputer\nimputer = SimpleImputer(strategy='mean') -> Option DQuick Check:
Correct import and strategy syntax = A [OK]
- Using 'method' instead of 'strategy'
- Not quoting 'mean' as a string
- Wrong import statement syntax
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)
Solution
Step 1: Calculate mean ignoring missing values
Column 0 mean = (1 + 7) / 2 = 4; Column 1 mean = (2 + 3) / 2 = 2.5Step 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.5Final Answer:
[[1. 2.] [4. 3.] [7. 2.5]] -> Option AQuick Check:
Missing values replaced by column means = B [OK]
- Not calculating mean correctly
- Leaving NaNs unchanged
- Expecting an error instead of imputation
from sklearn.impute import SimpleImputer X_train = [[1, 2], [None, 3], [7, None]] imputer = SimpleImputer(strategy='median') imputer.transform(X_train)
Solution
Step 1: Check method sequence
SimpleImputer requires fit() before transform() to learn statistics from data.Step 2: Verify data and strategy
Strategy 'median' is valid; None is accepted as missing; 2D list is acceptable.Final Answer:
Missing fit() call before transform() -> Option CQuick Check:
fit() must precede transform() = A [OK]
- Calling transform without fit
- Confusing strategy names
- Thinking None is invalid missing value
Solution
Step 1: Understand data leakage risk
Fitting imputer separately on test data leaks information from test set, causing biased evaluation.Step 2: Apply consistent imputation
Fit imputer only on training data to learn statistics, then apply same transformation to test data.Final Answer:
Fit the imputer on training data, then transform both training and test data -> Option AQuick Check:
Fit on train, transform both = C [OK]
- Fitting imputer separately on test data
- Filling test missing values with zeros arbitrarily
- Dropping too much data unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
