Bird
Raised Fist0
MLOpsdevops~5 mins

Feature engineering pipelines in MLOps - Commands & Configuration

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
Introduction
Feature engineering pipelines help automate the process of transforming raw data into useful features for machine learning models. They make sure the same steps are applied consistently during training and prediction, reducing errors and saving time.
When you want to clean and transform data before training a machine learning model.
When you need to apply the same data transformations to new data during model prediction.
When you want to organize multiple feature transformations into a single reusable workflow.
When you want to avoid repeating manual data processing steps and reduce mistakes.
When you want to track and reproduce feature transformations as part of your ML workflow.
Commands
Install scikit-learn library which provides tools to build feature engineering pipelines.
Terminal
pip install scikit-learn
Expected OutputExpected
Collecting scikit-learn Downloading scikit_learn-1.2.2-cp39-cp39-manylinux_2_17_x86_64.whl (23.3 MB) Installing collected packages: scikit-learn Successfully installed scikit-learn-1.2.2
Run the Python script that creates and applies a feature engineering pipeline to sample data.
Terminal
python feature_pipeline.py
Expected OutputExpected
Original data:\n age salary city\n0 25 50000 NY\n1 32 60000 SF\n2 40 80000 LA\n\nTransformed features:\n[[0. 0. 0. 0. 0. 1. ]\n [0.42857143 0.42857143 1. 1. 0. 0. ]\n [1. 1. 0. 0. 1. 0. ]]
Key Concept

If you remember nothing else from this pattern, remember: pipelines automate and standardize feature transformations to keep data consistent and reproducible.

Code Example
MLOps
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
import pandas as pd

# Sample raw data
raw_data = pd.DataFrame({
    'age': [25, 32, 40],
    'salary': [50000, 60000, 80000],
    'city': ['NY', 'SF', 'LA']
})

print("Original data:")
print(raw_data)

# Define which columns are numeric and which are categorical
numeric_features = ['age', 'salary']
categorical_features = ['city']

# Create transformers for numeric and categorical data
numeric_transformer = StandardScaler()
categorical_transformer = OneHotEncoder()

# Combine transformers into a preprocessor
preprocessor = ColumnTransformer(
    transformers=[
        ('num', numeric_transformer, numeric_features),
        ('cat', categorical_transformer, categorical_features)
    ])

# Create a pipeline that applies the preprocessor
feature_pipeline = Pipeline(steps=[('preprocessor', preprocessor)])

# Fit the pipeline on raw data and transform it
transformed_features = feature_pipeline.fit_transform(raw_data)

print("\nTransformed features:")
print(transformed_features.toarray() if hasattr(transformed_features, 'toarray') else transformed_features)
OutputSuccess
Common Mistakes
Applying feature transformations separately during training and prediction.
This causes inconsistent data processing and can lead to poor model performance or errors.
Use a pipeline object that bundles all transformations and apply it both during training and prediction.
Not fitting the pipeline on training data before transforming new data.
Transformers like scalers need to learn parameters from training data; skipping fit causes errors or wrong results.
Always call fit or fit_transform on training data before transforming new data.
Summary
Install scikit-learn to access pipeline and transformer tools.
Create a pipeline combining numeric scaling and categorical encoding.
Fit the pipeline on training data and transform it to get consistent features.

Practice

(1/5)
1. What is the main purpose of a feature engineering pipeline in MLOps?
easy
A. To automate and standardize data preparation steps
B. To deploy machine learning models to production
C. To monitor model performance after deployment
D. To collect raw data from external sources

Solution

  1. Step 1: Understand the role of feature engineering pipelines

    Feature engineering pipelines automate the process of transforming raw data into features for model training and testing.
  2. Step 2: Differentiate from other MLOps tasks

    Deploying models, monitoring, and data collection are separate tasks from feature engineering pipelines.
  3. Final Answer:

    To automate and standardize data preparation steps -> Option A
  4. Quick Check:

    Feature engineering pipeline = automate data prep [OK]
Hint: Feature pipelines automate data prep, not deployment or monitoring [OK]
Common Mistakes:
  • Confusing feature pipelines with model deployment
  • Thinking pipelines collect raw data
  • Mixing up monitoring with feature engineering
2. Which of the following is the correct way to define a simple feature engineering pipeline step using scikit-learn's Pipeline?
easy
A. pipeline = Pipeline([('scaler', StandardScaler()), ('pca', PCA(n_components=2))])
B. pipeline = Pipeline('scaler', StandardScaler(), 'pca', PCA(n_components=2))
C. pipeline = Pipeline({'scaler': StandardScaler(), 'pca': PCA(n_components=2)})
D. pipeline = Pipeline(StandardScaler(), PCA(n_components=2))

Solution

  1. Step 1: Recall scikit-learn Pipeline syntax

    Pipeline expects a list of tuples, each tuple with a name and a transformer object.
  2. Step 2: Check each option's syntax

    pipeline = Pipeline([('scaler', StandardScaler()), ('pca', PCA(n_components=2))]) correctly uses a list of tuples. Options B, C, and D use incorrect argument formats.
  3. Final Answer:

    pipeline = Pipeline([('scaler', StandardScaler()), ('pca', PCA(n_components=2))]) -> Option A
  4. Quick Check:

    Pipeline needs list of (name, transformer) tuples [OK]
Hint: Pipeline needs list of (name, transformer) tuples [OK]
Common Mistakes:
  • Passing arguments without list brackets
  • Using dict instead of list of tuples
  • Omitting step names in pipeline
3. Given the following pipeline code, what will be the output of pipeline.transform([[0, 0], [1, 1]])?
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

pipeline = Pipeline([
  ('scaler', StandardScaler()),
  ('pca', PCA(n_components=1))
])
pipeline.fit([[0, 0], [1, 1]])
result = pipeline.transform([[0, 0], [1, 1]])
print(result)
medium
A. Error: PCA requires more than one sample
B. [[0. 0.] [1. 1.]]
C. [[0.5] [0.5]]
D. [[-1.41421356] [ 1.41421356]]

Solution

  1. Step 1: Understand pipeline steps

    First, data is scaled to zero mean and unit variance, then PCA reduces to 1 component.
  2. Step 2: Calculate transformed output

    Scaling [[0,0],[1,1]] centers data, PCA finds principal component; output is approximately [[-1.41421356],[1.41421356]].
  3. Final Answer:

    [[-1.41421356] [ 1.41421356]] -> Option D
  4. Quick Check:

    Scaling + PCA output = [[-1.41421356] [ 1.41421356]] [OK]
Hint: Scaling centers data; PCA output is principal component values [OK]
Common Mistakes:
  • Expecting original data as output
  • Confusing PCA output shape
  • Assuming error due to small data
4. You have this pipeline code but it raises an error: ValueError: Expected 2D array, got 1D array instead. What is the likely cause?
pipeline = Pipeline([
  ('scaler', StandardScaler()),
  ('pca', PCA(n_components=1))
])
pipeline.fit([1, 2, 3, 4])
medium
A. Pipeline steps must be functions, not classes
B. Input to fit should be 2D array, not 1D list
C. StandardScaler requires integer inputs only
D. PCA cannot have n_components=1

Solution

  1. Step 1: Analyze error message

    The error says input is 1D but 2D is expected for fit method.
  2. Step 2: Check input format

    Input [1, 2, 3, 4] is a 1D list; fit expects 2D array like [[1], [2], [3], [4]].
  3. Final Answer:

    Input to fit should be 2D array, not 1D list -> Option B
  4. Quick Check:

    fit input shape must be 2D [OK]
Hint: fit() needs 2D array shape, not flat list [OK]
Common Mistakes:
  • Passing 1D list instead of 2D array
  • Misunderstanding PCA parameter limits
  • Thinking StandardScaler restricts input types
5. You want to create a feature engineering pipeline that handles missing values by filling them with the median, then scales features, and finally selects the top 3 features using a model-based selector. Which pipeline setup is correct?
hard
A. Pipeline([('scaler', StandardScaler()), ('imputer', SimpleImputer(strategy='median')), ('selector', SelectFromModel(estimator=RandomForestClassifier(), max_features=3))])
B. Pipeline([('selector', SelectFromModel(estimator=RandomForestClassifier(), max_features=3)), ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
C. Pipeline([('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler()), ('selector', SelectFromModel(estimator=RandomForestClassifier(), max_features=3))])
D. Pipeline([('imputer', SimpleImputer(strategy='mean')), ('selector', SelectFromModel(estimator=RandomForestClassifier(), max_features=3)), ('scaler', StandardScaler())])

Solution

  1. Step 1: Order pipeline steps logically

    Missing values must be handled first, then scaling, then feature selection.
  2. Step 2: Check each option's correctness

    Pipeline([('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler()), ('selector', SelectFromModel(estimator=RandomForestClassifier(), max_features=3))]) follows correct order and uses median for imputation. Pipeline([('scaler', StandardScaler()), ('imputer', SimpleImputer(strategy='median')), ('selector', SelectFromModel(estimator=RandomForestClassifier(), max_features=3))]) swaps imputer and scaler incorrectly. Pipeline([('selector', SelectFromModel(estimator=RandomForestClassifier(), max_features=3)), ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())]) starts with selector which needs complete data. Pipeline([('imputer', SimpleImputer(strategy='mean')), ('selector', SelectFromModel(estimator=RandomForestClassifier(), max_features=3)), ('scaler', StandardScaler())]) uses mean instead of median and wrong order.
  3. Final Answer:

    Pipeline([('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler()), ('selector', SelectFromModel(estimator=RandomForestClassifier(), max_features=3))]) -> Option C
  4. Quick Check:

    Impute -> scale -> select features [OK]
Hint: Impute missing -> scale -> select features in pipeline order [OK]
Common Mistakes:
  • Placing scaler before imputer
  • Selecting features before imputing missing values
  • Using mean instead of median when median is required