Reviewing Machine Learning Data Cleaning Code and Pipeline Design
Machine LearningModel answerLast updated
Evaluate an ML preprocessing codebase for design decisions, sklearn API conventions, data leakage prevention, code quality issues, and critical unit testing strategy.
You are conducting a code review of a team's feature engineering and data cleaning module. The codebase contains an OutlierHandler class along with three custom missing-value imputation classes (MeanImputer, MedianImputer, and ModeImputer).
Please provide a comprehensive review covering the following points:
- Functional Summary & Interface Design: Explain the core responsibility of
OutlierHandler. Why is separatingfitandtransformcritical for this functionality, especially within a production ML workflow? - Code Maintainability & API Best Practices: Identify key maintainability, naming, and architectural issues commonly found in custom preprocessors (e.g., sklearn API compliance, state management, magic numbers).
- Critical Testing Strategy: Describe and write out the single most important unit test you would implement for
OutlierHandler. Explain what specific failure mode it guards against. - Imputation Modules Review: Explain the purpose of the three imputation classes, identify at least two significant code quality issues (such as
from numpy import *), and suggest a cleaner design pattern.
Hints
Hint 1
Consider how data leakage occurs when test set statistics influence feature scaling or clipping.
Hint 2
Think about scikit-learn's estimator conventions, such as trailing underscores on learned attributes and returning self in fit.
Hint 3
Avoid testing implementation details: your primary unit test should verify that test data is transformed strictly using bounds calculated from training data.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Functional Summary & fit / transform Separation
Role of OutlierHandler
OutlierHandler is a stateful feature preprocessing transformer. Its primary responsibility is to identify statistical boundaries on numerical features (using metrics such as Interquartile Range [IQR] or Z-scores) and adjust extreme values (clipping/winsorizing) or mark them accordingly.
Why fit and transform Must Be Separated
Separating estimator training (fit) from data transformation (transform) is fundamental to machine learning engineering for four key reasons:
- Prevention of Data Leakage: Statistical bounds (e.g., $Q1 - 1.5 \times \text{IQR}$) must be computed exclusively on the training split. If
transformre-calculated statistics on validation or production data, information from future/unseen samples would leak into the transformation logic. - Train/Inference Parity: In production, inference often occurs on single-row payloads or mini-batches. Single-row inputs have zero variance, making local outlier calculation impossible. Storing state from
fitensures individual incoming production requests are evaluated against the training distribution. - Scikit-Learn Ecosystem Integration: Adhering to the standard API allows the handler to be integrated into
sklearn.pipeline.PipelineandColumnTransformer. This ensures cross-validation folds automatically fit preprocessors only on the inner training folds. - Efficiency: Stateful statistics are expensive to compute over millions of rows, but vectorized clipping using pre-computed bounds is extremely fast ($O(N)$ operations).
2. Maintainability & Code Quality Assessment
When auditing custom preprocessing components, the following architectural and code-quality issues frequently arise:
| Defect Category | Issue Description | Impact | Target Refactoring |
|---|---|---|---|
| Scikit-Learn Conventions | Attributes learned in fit lack trailing underscores (e.g., self.lower_bound vs self.lower_bound_). | Violates standard estimator contract; breaks sklearn.base.clone. | Name learned state with trailing underscores (self.lower_bound_, self.upper_bound_). |
| Method Chaining | fit() does not end with return self. | Cannot execute handler.fit(X).transform(X) or use inside Pipeline. | Add return self at the end of fit(). |
| State Guards | Calling transform() before fit() raises uninformative AttributeError. | Poor debugging developer experience. | Use sklearn.utils.validation.check_is_fitted or raise explicit NotFittedError. |
| Magic Numbers | Hardcoded values like 1.5 or 3.0 inside clipping methods. | Logic cannot be tuned or contextually adjusted per feature set. | Parametrize in __init__(self, factor=1.5, method="iqr"). |
| Side Effects | Mutating the input object directly inside transform(). | Mutates caller data structures in place, causing subtle pipeline bugs. | Operate on X.copy() or return a new NumPy array/DataFrame. |
| Performance | Iterating through rows or columns using explicit Python for loops. | Significant runtime bottlenecks on moderate-to-large datasets. | Use vectorized operations like np.clip or pd.DataFrame.clip. |
3. Critical Unit Test Implementation
The single most critical test must verify that transform() applies static bounds derived during fit(), rather than re-evaluating statistics on the incoming evaluation set.
If transform() calculates bounds dynamically on its input, test-set statistics leak into the feature matrix, breaking evaluation integrity.
import numpy as np
import pandas as pd
import pandas.testing as pdt
import pytest
# Assuming OutlierHandler is imported from feature_engineering
# from feature_engineering import OutlierHandler
def test_outlier_handler_uses_fitted_bounds_without_leakage():
# 1. Arrange: Training data where Q1=2.0, Q3=4.0, IQR=2.0
# Expected IQR bounds with factor=1.5:
# Lower bound = 2.0 - 1.5 * 2.0 = -1.0
# Upper bound = 4.0 + 1.5 * 2.0 = 7.0
df_train = pd.DataFrame({"feat_a": [1.0, 2.0, 3.0, 4.0, 5.0]})
# Evaluation data containing extreme values.
# If transform incorrectly recomputed bounds on df_test:
# Q1=-50, Q3=50, IQR=100 -> bounds would be [-200, 200], preventing clipping!
df_test = pd.DataFrame({"feat_a": [-100.0, 3.0, 100.0]})
df_test_clone = df_test.copy()
# 2. Act
handler = OutlierHandler(factor=1.5)
returned_state = handler.fit(df_train)
# Validate sklearn convention: fit returns self
assert returned_state is handler
transformed_df = handler.transform(df_test)
# 3. Assert: Outliers clipped according to TRAIN bounds [-1.0, 7.0]
expected_df = pd.DataFrame({"feat_a": [-1.0, 3.0, 7.0]})
pdt.assert_frame_equal(transformed_df, expected_df)
# Ensure input data frame was not modified in-place
pdt.assert_frame_equal(df_test, df_test_clone)
4. Review of the Imputation Classes
Purpose
The MeanImputer, MedianImputer, and ModeImputer classes fill missing values (NaN/None) in feature columns using summary metrics learned from training data.
Key Code Quality & Architecture Issues
-
Namespace Pollution via Wildcard Imports (
from numpy import *):- Scope Contamination: Overwrites core Python built-ins like
sum,min,max, andanywith NumPy equivalents that behave differently on non-array iterables. - Maintainability: Makes variable and function origins ambiguous to maintainers and static analysis tools.
- Fix: Use explicit aliased imports:
import numpy as np.
- Scope Contamination: Overwrites core Python built-ins like
-
Violation of DRY (Don't Repeat Yourself) Principles:
- Writing three separate classes (
MeanImputer,MedianImputer,ModeImputer) leads to near-identical boilerplate acrossfitandtransformstate handling. - Fix: Consolidate into a single transformer matching
sklearn.impute.SimpleImputer(strategy="mean"), or implement a shared base class with abstract strategy execution.
- Writing three separate classes (