CodeBlanks Logo Icon CodeBlanks

Summary - Data preprocessing

In this group you learned data cleaning, missing data, and label encoding.

Summary: data preprocessing

The steps data goes through before the model:

  1. Cleaning: duplicates, spelling differences, outliers.
  2. Missing values: dropna or SimpleImputer.
  3. Types: to_numeric, astype.
  4. Encoding: LabelEncoder for labels, one-hot for unordered features.
  5. Splitting: train_test_split, with stratify and 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

model.py
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 yaz

Sample solution

model.py
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.

Question
X_test = imp.____(X_test)
Answer
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

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation