Review a Fit/Transform Preprocessing Module and Write a Key Test
Data Structure DesignModel answerLast updated
Review a small Python preprocessing module with an outlier-capping class and three imputers: explain its purpose, justify fit/transform separation, critique style and imports, and write one key unit test.
Scenario
You are reviewing a pull request for a small Python data-preprocessing module. It contains:
- an
OutlierHandlerclass that treats extreme numeric values, and - three imputer classes that fill in missing values.
You do not have to run the code. Assume it follows the typical shape of such modules: OutlierHandler learns per-column limits from data and then applies them, and the imputers each use a different statistic (for example mean, median, or most frequent value) to fill gaps.
What to cover
- Purpose. Give a high-level summary of what
OutlierHandleraccomplishes and how it does so. - Design. Explain why it is beneficial for the class to expose learning (
fit) and applying (transform) as two separate methods. - Style review. Identify the coding-style and import problems you would expect in the three imputer classes. For each, say why it matters and how you would fix it.
- Testing. Write, by hand, one unit test for
OutlierHandlerthat you consider the most valuable. Explain what bug it would catch and use a clear expected-versus-actual comparison.
Expectations
- Reference conventions from scikit-learn estimators and PEP 8.
- Be concrete: name specific problems and specific fixes rather than generalities.
- The test should be small, deterministic, and include hand-computed expected values.
Hints
Hint 1
Think about what would go wrong if the limits were recomputed from whatever data is passed to the applying step, for example when scoring a single row in production or evaluating on a test set.
Hint 2
For the style review, look at how names are imported (wildcard imports), whether the three imputers duplicate logic, naming conventions, whether fit returns self, and whether the input data is modified.
Hint 3
For the test, fit on a tiny dataset where you can compute the quartiles by hand, transform a different dataset containing values far outside the range, and assert that results are capped at the training-derived limits and that the input was not changed.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
The code is not shown, so this answer assumes the common shape of such a module:
OutlierHandlerlearns per-column bounds and caps values outside them.- Three imputers (mean, median, mode) fill missing values.
- The imputers share the usual smells: wildcard imports, copy-pasted logic, and inconsistent naming.
1. What OutlierHandler does
It is a stateful preprocessing step that limits the influence of extreme values.
fit(X)learns thresholds from training data and stores them on the object. A typical rule is IQR-based:lower = Q1 - k*IQR,upper = Q3 + k*IQR, withk = 1.5. A z-score cutoff is an alternative.transform(X)applies the stored thresholds to any dataset. It usually caps (winsorizes) values to the bounds rather than dropping rows, so row count and index alignment are preserved.
In one sentence: it makes downstream models less sensitive to extremes, reproducibly, using statistics learned only from training data.
2. Why separate fit and transform
- No leakage. If the bounds were recomputed on each batch, test data would shape its own preprocessing. Bounds learned on the training set must be reused for validation, test, and serving.
- Single-row scoring works. Quantiles of one production row are meaningless; stored bounds make it well defined.
- Reproducibility. The fitted object can be pickled and versioned with the model, giving identical behavior everywhere.
- Composability. Following the scikit-learn contract (
fitreturnsself, learned attributes end with_,fit_transformas a convenience) lets the class work inPipeline,ColumnTransformer, and cross-validation, where each fold refits correctly. - Efficiency. Fit once, transform many times.
3. Style and import critique of the imputers
| Problem | Why it matters | Fix |
|---|---|---|
from numpy import * | Pollutes the namespace, shadows builtins like sum, any, all with different semantics, hides where names come from, defeats linters. PEP 8 discourages it. | import numpy as np, import pandas as pd |
| Unused imports, imports mid-file | Noise, can mask circular imports | All imports at top, grouped stdlib / third-party / local; remove unused ones |
meanImputer, fitData, Fill_Value | Violates PEP 8 | CapWords classes, snake_case functions and variables, UPPER_CASE constants |
| Three near-identical classes | Violates DRY; a fix in one is missed in others | A shared base class, or one class with a strategy argument, where only the statistic differs |
Statistic computed inside transform | Leakage, same issue as above | Compute in fit, store as fill_values_ |
fit returns None | Breaks chaining and pipelines | return self |
| Mutates the caller's data | Surprising side effects | Operate on a copy |
| No "was it fitted?" check | Obscure AttributeError later | Raise a clear error |
Bare except:, magic numbers, no docstrings or type hints | Hides real errors, hurts readability | Catch specific exceptions, name constants, document parameters |
Enforce the mechanical rules with black, isort, and ruff/flake8 in CI so review can focus on design.
4. The key unit test
The most valuable test checks the central contract: bounds are learned in fit and reused unchanged in transform. One test can verify:
- values outside the training bounds are capped to exactly those bounds,
- in-range values are untouched,
- bounds are not recomputed from the new data,
- the input DataFrame is not mutated,
- NaN passes through (imputation is a separate concern).
import numpy as np
import pandas as pd
import pytest
class OutlierHandler:
"""Cap values outside [Q1 - k*IQR, Q3 + k*IQR] learned during fit."""
def __init__(self, k: float = 1.5):
if k < 0:
raise ValueError("k must be non-negative")
self.k = k
def fit(self, X: pd.DataFrame, y=None) -> "OutlierHandler":
numeric = X.select_dtypes(include="number")
q1 = numeric.quantile(0.25)
q3 = numeric.quantile(0.75)
iqr = q3 - q1
self.lower_ = q1 - self.k * iqr
self.upper_ = q3 + self.k * iqr
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
if not hasattr(self, "lower_"):
raise RuntimeError("OutlierHandler must be fitted before transform")
out = X.copy()
cols = self.lower_.index
out[cols] = out[cols].clip(lower=self.lower_, upper=self.upper_, axis=1)
return out
def fit_transform(self, X: pd.DataFrame, y=None) -> pd.DataFrame:
return self.fit(X, y).transform(X)
def test_transform_caps_using_bounds_learned_in_fit():
# Train: Q1 = 2, Q3 = 4, IQR = 2 -> bounds [-1, 7]
train = pd.DataFrame({"x": [1.0, 2.0, 3.0, 4.0, 5.0]})
handler = OutlierHandler(k=1.5).fit(train)
test = pd.DataFrame({"x": [-100.0, 3.0, 100.0, np.nan]})
test_before = test.copy()
actual = handler.transform(test)
expected = pd.DataFrame({"x": [-1.0, 3.0, 7.0, np.nan]})
pd.testing.assert_frame_equal(actual, expected)
pd.testing.assert_frame_equal(test, test_before)
assert handler.lower_["x"] == -1.0
assert handler.upper_["x"] == 7.0
def test_transform_before_fit_raises():
with pytest.raises(RuntimeError):
OutlierHandler().transform(pd.DataFrame({"x": [1.0]}))
Why the expected values are right
With pandas' default linear interpolation, [1, 2, 3, 4, 5] gives Q1 = 2 and Q3 = 4, so IQR = 2 and the bounds are 2 - 3 = -1 and 4 + 3 = 7. If transform wrongly recomputed bounds from the test frame, the extremes of -100 and 100 would stretch the limits and would not be mapped to -1 and 7. The assertion therefore fails exactly when leakage or recomputation is introduced.
Complexity
fit: quantiles need sorting or selection per column, so O(n log n * d) time and O(d) extra space for the bounds.transform: one pass, O(n * d) time, plus O(n * d) space for the defensive copy.
Edge cases and common mistakes
- Constant column: IQR is 0, so bounds collapse to that value. Decide whether that is acceptable.
- Non-numeric columns must be left alone, not crash the handler.
- Columns that are all NaN produce NaN bounds; clipping with NaN bounds does nothing, which should be documented or rejected.
- Columns missing at transform time should raise a clear error.
- Common mistakes in answers: only describing the test in words without concrete expected numbers, testing on the same data used for fit (which cannot detect recomputation), and forgetting to check that the input is not mutated.