Summary - Data preprocessing
- Machine Learning course
- Beginner
- Lesson 24/112
- 6 min
In this group you learned data cleaning, missing data, and label encoding.
Summary: data preprocessing
The steps data goes through before the model:
- Cleaning: duplicates, spelling differences, outliers.
- Missing values:
dropnaorSimpleImputer. - Types:
to_numeric,astype. - Encoding:
LabelEncoderfor labels, one-hot for unordered features. - Splitting:
train_test_split, withstratifyand a validation set when needed.
The golden rule: every learned step such as filling and encoding is fit only on the training data.
Practice Leak-free filling
fit a SimpleImputer(strategy="mean") on X_train only, then transform X_test and print the result.
Starter code
import numpy as np
from sklearn.impute import SimpleImputer
X_train = np.array([[2.0], [4.0], [6.0]])
X_test = np.array([[np.nan], [10.0]])
# buraya yazSample solution
import numpy as np
from sklearn.impute import SimpleImputer
X_train = np.array([[2.0], [4.0], [6.0]])
X_test = np.array([[np.nan], [10.0]])
imp = SimpleImputer(strategy="mean")
imp.fit(X_train)
print(imp.transform(X_test))Expected output
[[ 4.] [10.]]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How should SimpleImputer be used on the test data?
- fit_transform again on the test data
- It shouldn't be used at all
- It should be fitted on all the data
- Only transform, with the object fitted on training Correct answer
Explanation: The test data's mean must not leak into training; the same learned value is applied.
2 Apply the filling learned on training to the test data.
X_test = imp.____(X_test)
X_test = imp.transform(X_test)
Explanation: transform uses the values learned during fit.
3 Match the steps with the tools.
| Term | Meaning |
|---|---|
Filling missing values |
SimpleImputer |
Text label |
LabelEncoder |
Unordered feature |
OneHotEncoder |
Balanced split |
stratify |