Bird
Raised Fist0
ML Pythonml~12 mins

ColumnTransformer for mixed types in ML Python - Model Pipeline Trace

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Model Pipeline - ColumnTransformer for mixed types

This pipeline shows how to handle different types of data columns separately using ColumnTransformer. Numeric columns are scaled, and categorical columns are converted to numbers. This helps the model learn better from mixed data.

Data Flow - 4 Stages
1Raw Data Input
1000 rows x 5 columnsOriginal dataset with 3 numeric and 2 categorical columns1000 rows x 5 columns
[{'age': 25, 'income': 50000, 'score': 0.8, 'gender': 'M', 'city': 'NY'}, ...]
2Preprocessing with ColumnTransformer
1000 rows x 5 columnsScale numeric columns and one-hot encode categorical columns1000 rows x 7 columns
[[0.1, -0.2, 0.5, 1, 0, 0, 1], ...] # scaled numeric + encoded categorical
3Train/Test Split
1000 rows x 7 columnsSplit data into 800 training and 200 testing rowsTrain: 800 rows x 7 columns, Test: 200 rows x 7 columns
Train features shape: (800, 7), Test features shape: (200, 7)
4Model Training
800 rows x 7 columnsTrain logistic regression model on processed dataTrained model
Model learns weights for 7 input features
Training Trace - Epoch by Epoch
Loss
0.65 |*****
0.50 |****
0.40 |***
0.35 |**
0.30 |*
Epochs -> 1 2 3 4 5
EpochLoss ↓Accuracy ↑Observation
10.650.60Model starts with moderate loss and accuracy
20.500.75Loss decreases and accuracy improves
30.400.82Model continues to learn patterns
40.350.85Loss decreases steadily, accuracy rises
50.300.88Training converges with good accuracy
Prediction Trace - 4 Layers
Layer 1: Input sample
Layer 2: ColumnTransformer preprocessing
Layer 3: Model prediction (logistic regression)
Layer 4: Threshold decision
Model Quiz - 3 Questions
Test your understanding
What does the ColumnTransformer do to categorical columns?
AConverts them into numbers using one-hot encoding
BScales them between 0 and 1
CDrops them from the dataset
DLeaves them unchanged
Key Insight
Using ColumnTransformer allows the model to handle numeric and categorical data properly by applying the right transformations to each type. This improves learning and prediction accuracy.

Practice

(1/5)
1. What is the main purpose of using ColumnTransformer in machine learning?
easy
A. To train multiple models on the same dataset
B. To apply different preprocessing steps to different columns in a dataset
C. To visualize data distributions
D. To split data into training and testing sets

Solution

  1. Step 1: Understand the role of ColumnTransformer

    ColumnTransformer allows applying different transformations to different columns, such as scaling numbers and encoding text.
  2. Step 2: Compare with other options

    Training models, visualizing data, or splitting data are different tasks not handled by ColumnTransformer.
  3. Final Answer:

    To apply different preprocessing steps to different columns in a dataset -> Option B
  4. Quick Check:

    ColumnTransformer = Different preprocessing per column [OK]
Hint: Think: Different columns, different treatments [OK]
Common Mistakes:
  • Confusing ColumnTransformer with model training
  • Thinking it splits data instead of transforming
  • Assuming it visualizes data
2. Which of the following is the correct way to import ColumnTransformer from scikit-learn?
easy
A. from sklearn.feature_extraction import ColumnTransformer
B. from sklearn.preprocessing import ColumnTransformer
C. from sklearn.pipeline import ColumnTransformer
D. from sklearn.compose import ColumnTransformer

Solution

  1. Step 1: Recall the module for ColumnTransformer

    ColumnTransformer is part of the compose module in scikit-learn.
  2. Step 2: Verify other options

    Preprocessing, pipeline, and feature_extraction modules do not contain ColumnTransformer.
  3. Final Answer:

    from sklearn.compose import ColumnTransformer -> Option D
  4. Quick Check:

    ColumnTransformer is in compose module [OK]
Hint: Remember: compose module for combining transformers [OK]
Common Mistakes:
  • Importing from preprocessing instead of compose
  • Confusing pipeline with compose
  • Trying to import from feature_extraction
3. Given the code below, what will be the output of print(transformed_data)?
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
import numpy as np

X = np.array([[1, 'red'], [2, 'blue'], [3, 'green']])

ct = ColumnTransformer([
    ('num', StandardScaler(), [0]),
    ('cat', OneHotEncoder(), [1])
])

transformed_data = ct.fit_transform(X)
print(transformed_data)
medium
A. A numpy array with scaled numbers and one-hot encoded colors
B. A list of original values without changes
C. An error because StandardScaler cannot handle strings
D. A numpy array with only scaled numbers

Solution

  1. Step 1: Understand ColumnTransformer setup

    Column 0 (numbers) is scaled; column 1 (colors) is one-hot encoded.
  2. Step 2: Predict output structure

    Output is a numpy array combining scaled numeric values and one-hot encoded categorical values.
  3. Final Answer:

    A numpy array with scaled numbers and one-hot encoded colors -> Option A
  4. Quick Check:

    Mixed types transformed correctly = scaled + one-hot [OK]
Hint: Remember: ColumnTransformer applies each transformer to specified columns [OK]
Common Mistakes:
  • Expecting original data without transformation
  • Thinking StandardScaler will fail on mixed data
  • Ignoring one-hot encoding effect
4. What is wrong with the following code snippet using ColumnTransformer?
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
import numpy as np

X = np.array([[1, 'red'], [2, 'blue'], [3, 'green']])

ct = ColumnTransformer([
    ('num', StandardScaler(), [0, 1]),
    ('cat', OneHotEncoder(), [1])
])

transformed_data = ct.fit_transform(X)
medium
A. StandardScaler is applied to a string column causing an error
B. OneHotEncoder is applied to a numeric column causing an error
C. ColumnTransformer requires numeric data only
D. No error, code runs fine

Solution

  1. Step 1: Check columns assigned to StandardScaler

    StandardScaler is applied to columns 0 and 1, but column 1 contains strings.
  2. Step 2: Understand why this causes an error

    StandardScaler cannot process string data, so this will raise a type error.
  3. Final Answer:

    StandardScaler is applied to a string column causing an error -> Option A
  4. Quick Check:

    Scaler on strings = error [OK]
Hint: Scaler only works on numeric columns [OK]
Common Mistakes:
  • Applying scaler to categorical columns
  • Assuming ColumnTransformer auto-detects types
  • Ignoring column indices in transformer
5. You have a dataset with numeric columns ['age', 'income'] and categorical columns ['city', 'gender']. You want to scale numeric columns and one-hot encode categorical columns using ColumnTransformer. Which code snippet correctly sets this up?
hard
A. ColumnTransformer([('num', OneHotEncoder(), ['age', 'income']), ('cat', StandardScaler(), ['city', 'gender'])])
B. ColumnTransformer([('num', StandardScaler(), ['city', 'gender']), ('cat', OneHotEncoder(), ['age', 'income'])])
C. ColumnTransformer([('num', StandardScaler(), ['age', 'income']), ('cat', OneHotEncoder(), ['city', 'gender'])])
D. ColumnTransformer([('num', StandardScaler(), ['age']), ('cat', OneHotEncoder(), ['income', 'city', 'gender'])])

Solution

  1. Step 1: Identify correct transformers for each column type

    Numeric columns should be scaled with StandardScaler; categorical columns should be one-hot encoded.
  2. Step 2: Match columns to transformers correctly

    ColumnTransformer([('num', StandardScaler(), ['age', 'income']), ('cat', OneHotEncoder(), ['city', 'gender'])]) assigns numeric columns to StandardScaler and categorical columns to OneHotEncoder correctly.
  3. Final Answer:

    ColumnTransformer([('num', StandardScaler(), ['age', 'income']), ('cat', OneHotEncoder(), ['city', 'gender'])]) -> Option C
  4. Quick Check:

    Numeric scaled + categorical one-hot = ColumnTransformer([('num', StandardScaler(), ['age', 'income']), ('cat', OneHotEncoder(), ['city', 'gender'])]) [OK]
Hint: Match scaler to numbers, encoder to categories [OK]
Common Mistakes:
  • Swapping transformers between numeric and categorical
  • Mixing columns in wrong transformer
  • Leaving out columns