KatInterview

Review a Feature Preprocessing Class

Machine LearningModel answer
MediumModel answerMachine Learningcode-reviewdata-preprocessingdata-leakage

Last 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.