Bird
Raised Fist0
ML Pythonml~8 mins

ColumnTransformer for mixed types in ML Python - Model Metrics & Evaluation

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
Metrics & Evaluation - ColumnTransformer for mixed types
Which metric matters for this concept and WHY

When using a ColumnTransformer to handle mixed data types, the key metric depends on the task:

  • For classification: Accuracy, Precision, Recall, and F1-score matter because they show how well the model predicts different classes after proper data processing.
  • For regression: Mean Squared Error (MSE) or R-squared show how well the model predicts continuous values after transforming columns correctly.

Why? Because ColumnTransformer ensures each data type is processed properly (e.g., numbers scaled, categories encoded). If the transformer works well, the model's performance metrics improve.

Confusion matrix or equivalent visualization (ASCII)

For classification tasks, a confusion matrix helps understand model errors after using ColumnTransformer:

          Predicted
          Pos   Neg
Actual Pos  TP    FN
       Neg  FP    TN

Example with numbers:

          Predicted
          Pos   Neg
Actual Pos  50    10
       Neg  5     35

Here, TP=50, FN=10, FP=5, TN=35. These numbers come after the model uses transformed data from ColumnTransformer.

Precision vs Recall tradeoff with concrete examples

Using ColumnTransformer correctly affects precision and recall:

  • Precision = TP / (TP + FP): How many predicted positives are actually positive.
  • Recall = TP / (TP + FN): How many actual positives were found.

Example: If categorical data is not encoded well, the model may confuse classes, lowering precision (more false positives) or recall (more false negatives).

Tradeoff: For spam detection, high precision is important (avoid marking good emails as spam). For disease detection, high recall is key (catch all sick patients).

What "good" vs "bad" metric values look like for this use case

After using ColumnTransformer:

  • Good metrics: Accuracy > 80%, Precision and Recall balanced above 75%, F1-score high (close to 1).
  • Bad metrics: Accuracy near random guess (e.g., 50% for binary), Precision or Recall very low (below 50%), indicating poor data handling.

Good metrics mean the mixed data was transformed well and the model learned patterns correctly.

Metrics pitfalls (accuracy paradox, data leakage, overfitting indicators)
  • Accuracy paradox: High accuracy can be misleading if classes are imbalanced. For example, if 95% data is one class, accuracy can be high but model useless.
  • Data leakage: If ColumnTransformer is fit on all data before splitting, test data leaks into training, inflating metrics.
  • Overfitting: Very high training accuracy but low test accuracy means model memorized training data, possibly due to improper transformations.
  • Ignoring data types: Not using ColumnTransformer properly can mix numeric and categorical data, hurting model performance.
Self-check question

Your model uses ColumnTransformer on mixed data. It shows 98% accuracy but only 12% recall on the positive class (e.g., fraud). Is it good for production? Why or why not?

Answer: No, it is not good. The low recall means the model misses most positive cases (fraud). Even with high accuracy, it fails to catch important cases, which is critical in fraud detection.

Key Result
ColumnTransformer improves model metrics by correctly processing mixed data types, but precision and recall must be balanced to ensure real-world usefulness.

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