Review a Feature Preprocessing Class
Machine LearningModel answerLast updated
Critique a Python class that scales numerical features and encodes categorical ones, explaining its design pattern and identifying bugs.
You're reviewing a Python class used in a machine learning pipeline. The class preprocesses tabular data by standardizing numeric columns and encoding categorical columns.
class Preprocessor:
def __init__(self, num_cols=[], cat_cols=[]):
self.num_cols = num_cols
self.cat_cols = cat_cols
self.means = {}
self.stds = {}
self.categories = {}
def fit(self, df):
for c in self.num_cols:
df[c] = df[c].fillna(df[c].mean())
self.means[c] = df[c].mean()
self.stds[c] = df[c].std()
for c in self.cat_cols:
self.categories[c] = df[c].unique().tolist()
def transform(self, df):
for i, row in df.iterrows():
for c in self.num_cols:
if pd.isna(row[c]):
df.at[i, c] = df[c].mean()
df.at[i, c] = (df.at[i, c] - self.means[c]) / self.stds[c]
for c in self.cat_cols:
for cat in self.categories[c]:
df[f"{c}_{cat}"] = (df[c] == cat).astype(int)
df.drop(columns=c, inplace=True)
print("done")
return df
Answer the following:
a) Describe what this class does at a high level.
b) Explain why the logic is split into fit() and transform() methods rather than a single processing function.
c) Identify problems in this implementation, from critical correctness issues to maintainability concerns.
Hints
Hint 1
Consider what happens when transform() is called on test data versus training data—are the statistics always the same?
Hint 2
Think about performance: how does iterrows() with df.at[] scale compared to vectorized operations?
Hint 3
Watch for Python gotchas like mutable default arguments and in-place DataFrame modifications.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
a) What the class does
This is a stateful feature preprocessor for tabular data. It handles two types of columns:
- Numerical columns: Fills missing values with the column mean, then standardizes values using z-score normalization: (x - μ) / σ
- Categorical columns: Performs one-hot encoding based on the unique values observed
The fit method learns statistics from a dataset (means, standard deviations, category vocabularies), and transform applies those learned parameters to new data.
b) Why separate fit() and transform()?
The two-step pattern is fundamental to correct machine learning pipelines:
Preventing data leakage
Statistics must be computed exclusively from training data. If you calculate the mean or standard deviation from test data during transformation, you're leaking information from your evaluation set into preprocessing, which artificially inflates performance metrics. The same principle applies in cross-validation—each fold must fit only on its training partition.
Training-serving consistency
At inference time, a single prediction request has no meaningful mean or vocabulary of its own. You must apply the exact same transformation parameters learned during training. Separating fit and transform makes these parameters an explicit artifact that can be reused.
Pipeline composability
Any transformer following this pattern can be chained in scikit-learn pipelines, used in grid search, and swapped without changing downstream code. It's a standard contract.
Performance
Computing statistics is expensive and happens once during fit. The transform step just applies stored values, which is fast and suitable for real-time serving.
Auditability and reproducibility
The fitted parameters can be serialized, versioned alongside the model, and inspected later—critical in regulated industries where you must explain exactly how features were computed.
c) Problems (ordered by severity)
Critical: Correctness and Data Leakage
-
Data leakage in transform(): The line
df.at[i, c] = df[c].mean()computes the mean of the current DataFrame being transformed, not the training mean stored inself.means. This completely defeats the purpose of the fit/transform split. For a single-row prediction, this mean would be the row itself or NaN. -
Imputation mutates input before computing statistics: In
fit(), the code fills NaNs then computes mean and std on the already-filled data. This deflates the standard deviation estimate and silently modifies the caller's DataFrame. -
Division by zero: A constant column (std = 0) will produce inf or NaN values during standardization.
-
No handling of unseen categories: Values in
transformthat weren't infitsilently create all-zero rows. There's also no handling of NaN categorical values. -
No schema validation: The code doesn't verify that expected columns exist or have the right types. Schema drift in production would silently corrupt features.
Design and API Issues
-
Mutable default arguments:
num_cols=[]creates a single shared list across all instances—a classic Python bug. Should benum_cols=None. -
Mutates input DataFrames: Both methods modify
dfin place withdf[c] = ...andinplace=True. Callers don't expect their DataFrames to be altered. -
No "fitted" state check: Calling
transformbeforefitraises an obscure KeyError instead of a clear error message. -
Missing return self in fit(): By convention,
fitshould returnselfto enable method chaining. There's also nofit_transformconvenience method. -
Not scikit-learn compatible: Doesn't inherit from
BaseEstimatororTransformerMixin, so it can't be used inPipeline,GridSearchCV, or cloned.
Performance
-
Catastrophically slow iteration: Using
iterrows()withdf.at[]writes is 100–1000× slower than vectorized operations like(df[cols] - self.means) / self.stds. The repeateddf[c].mean()call inside the loop makes it O(n²). -
Inefficient column construction: Creating one-hot columns one at a time in a loop fragments memory. Should use
pd.get_dummiesor build all columns at once.
Maintainability
-
No logging, validation, or documentation: Uses
print("done")instead of proper logging. No type hints, docstrings, or input validation. -
Mixed responsibilities: Combines imputation, scaling, and encoding. Separate, composable transformers (or scikit-learn's
ColumnTransformer) would be clearer and more testable.
How to fix it
A corrected version would:
- Use
Nonedefaults and avoid mutating inputs (create copies) - Store imputation values separately and apply them correctly in
transform - Replace
iterrows()with vectorized pandas operations - Add
check_is_fittedguards and returnselffromfit - Handle unseen categories explicitly (e.g., ignore, error, or use an "unknown" category)
- Clamp or skip zero-variance columns
- Inherit from
BaseEstimatorandTransformerMixin
In production, you'd typically use scikit-learn's built-in transformers (StandardScaler, OneHotEncoder) in a ColumnTransformer unless you have a specific reason to write custom logic.
Common mistake: Candidates sometimes miss the leakage bug in transform() or dismiss performance issues as "premature optimization" without recognizing that iterrows is genuinely unusable at scale.
Time complexity: Current implementation is O(n²m) for n rows and m numeric columns due to the repeated mean calculation. Correct vectorized version is O(nm).