Reviewing a Venv Setup Script and Data-Prep Transformers
Machine LearningModel answerLast updated
Walk through a virtual-environment shell script, then review an outlier-clipping transformer and three imputers for design, style and testability, and write a key unit test.
You are reviewing a teammate's data-science repository. Answer the questions below as you would in a code review conversation.
Part 1: Environment script
#!/bin/bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
python3 -m venv "$ROOT/.venv"
source "$ROOT/.venv/bin/activate"
pip install --upgrade pip
pip install -r "$ROOT/requirements.txt"
python -m ipykernel install --user --name analysis-env
echo "done"
- Explain what each line does and why it is there.
- What does shell scripting give a team doing data-science engineering?
Part 2: Outlier clipping
class OutlierHandler:
def __init__(self, cols, k=1.5):
self.cols = cols
self.k = k
def fit(self, df):
self.bounds = {}
for c in self.cols:
q1, q3 = df[c].quantile([0.25, 0.75])
iqr = q3 - q1
self.bounds[c] = (q1 - self.k * iqr, q3 + self.k * iqr)
return self
def transform(self, df):
for c, (lo, hi) in self.bounds.items():
df[c] = df[c].clip(lo, hi)
print("clipping finished")
return df
- Describe what the class is for.
- Why is it good practice to keep
fit()andtransform()as separate methods? - List the style and design problems you see.
- Write the single unit test you consider most valuable.
Part 3: Imputation
from numpy import *
class MeanFiller: # numeric columns: learns per-column means in fit, fills NaN in transform
class ModeFiller: # categorical columns: learns most frequent value, fills missing entries
class ConstantFiller: # fills every missing entry with a fixed user-supplied value
- Summarize at a high level what these three classes do.
- What style problems do you see in the script, in particular the first line (
from numpy import *)? Justify each one.
Hints
Hint 1
For the shell script, think about what happens if one command fails midway, and what makes the environment identical on another machine.
Hint 2
Ask where the quartiles are computed. Which dataset should they come from, and what happens at serving time when only one row arrives?
Hint 3
For the unit test, fit on one dataset and transform a different one. Check that the bounds match the training data and that the input frame is unchanged.
Hint 4
For the wildcard import, list which built-in names NumPy would overwrite and what that does to a reader trying to trace where a name comes from.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: The environment script
#!/bin/bashselects the interpreter.#!/usr/bin/env bashis more portable across macOS, Linux and CI images.set -euo pipefailis strict mode.-estops at the first failing command,-umakes unset variables an error, andpipefailmakes a pipeline fail if any stage fails. Without it a failed install could be ignored and the script would still print "done".ROOT=...resolves the script's own absolute directory, so it works from any working directory.python3 -m venvcreates an isolated interpreter and site-packages inside the project.source .../activatemakespythonandpiprefer to the venv for the rest of this script only. It does not affect the caller's shell.pip install --upgrade pipavoids bugs in old resolvers.pip install -r requirements.txtinstalls dependencies. The result is only reproducible if the file pins exact versions or comes from a lock file.ipykernel installregisters the environment as a named Jupyter kernel, so notebooks use the same packages as scripts.echogives the user feedback.
Why shell scripts help data-science engineering
- One command sets up a laptop, CI runner or server, which reduces "works on my machine" problems.
- They glue together tools that have no common Python API: git, Docker, DVC, cloud CLIs, Spark submit.
- They are easy to schedule (cron, Airflow
BashOperator) and chain into pipelines. - They are versioned and reviewable, and exit codes plug directly into orchestrators.
- Caveats: they get unwieldy past roughly 100 lines, and portability and error handling are weaker than in Python. Put real logic in Python and keep the shell thin.
Part 2: OutlierHandler
Purpose. It learns per-column bounds with the IQR rule, [Q1 - k*IQR, Q3 + k*IQR], and clips (winsorizes) values outside them. This limits the influence of extreme values on downstream models without dropping rows.
Why separate fit and transform
- No leakage. Bounds come from training data only. Recomputing them on validation or test data leaks information and makes metrics optimistic.
- Serving consistency. One production row has no meaningful quantiles. It needs stored bounds.
- Pipeline compatibility. Cross-validation can refit per fold, and
PipelineandGridSearchCVrely on the contract. - Inspectability and persistence. Learned state can be asserted in tests and saved with
joblib.
Problems in the class
transformmutates the caller's DataFrame in place. Copy first.- No check that
fitwas called. The failure is an obscureAttributeError. printshould belogging, or nothing at all.- It does not inherit
BaseEstimatorandTransformerMixin, so there is noget_params,fit_transformorclonesupport. - Learned attributes should end in an underscore (
bounds_) by convention. Constructor arguments should not be changed. - Edge cases are unhandled: NaNs, non-numeric columns, missing columns at transform time, and constant columns where IQR is 0 (every other value gets clipped to the constant).
- No docstrings or type hints.
kshould be validated as non-negative.
Cleaned version and the most valuable test
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_is_fitted
class OutlierHandler(BaseEstimator, TransformerMixin):
def __init__(self, cols, k=1.5):
self.cols = cols
self.k = k
def fit(self, X, y=None):
self.bounds_ = {}
for c in self.cols:
q1, q3 = X[c].quantile([0.25, 0.75])
iqr = q3 - q1
self.bounds_[c] = (q1 - self.k * iqr, q3 + self.k * iqr)
return self
def transform(self, X):
check_is_fitted(self, "bounds_")
out = X.copy()
for c, (lo, hi) in self.bounds_.items():
out[c] = out[c].clip(lo, hi)
return out
def test_uses_training_bounds_and_does_not_mutate():
train = pd.DataFrame({"x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
test = pd.DataFrame({"x": [-100, 5, 1000]})
snapshot = test.copy()
h = OutlierHandler(cols=["x"]).fit(train)
lo, hi = h.bounds_["x"]
result = h.transform(test)
assert result["x"].tolist() == [lo, 5, hi] # training bounds, not test stats
pd.testing.assert_frame_equal(test, snapshot) # input untouched
This single test guards against the two most damaging bugs: leakage (bounds recomputed from test data) and silent mutation of caller data. Because the test frame contains extreme values, recomputing bounds on it would give different results and fail the assertion.
Complexity: fit and transform are O(nd) for n rows and d columns. Memory for learned state is O(d), plus O(nd) for the copy.
Part 3: The imputers
What they do. Each follows the fit/transform pattern:
MeanFillerlearns a per-column mean on numeric data and fills NaNs with it.ModeFillerlearns the most frequent category per column and fills missing entries.ConstantFillerfills with a fixed value, which is useful as a baseline or to flag "missing" as its own category.
Style problems
from numpy import *is the headline issue.- It dumps hundreds of names into the module namespace.
- It shadows built-ins such as
sum,min,max,abs,roundandanywith NumPy versions that behave differently (axis arguments, generator handling), which causes subtle bugs. - Readers and linters can no longer tell where a name comes from.
- Fix:
import numpy as npand callnp.nanmean, and so on.
- Duplicated structure. The three classes repeat the same skeleton. A single base class or a
strategyparameter (as inSimpleImputer) removes duplication, and in practice sklearn'sSimpleImputeralready covers all three. - Mutating inputs and missing fitted-state checks, as in
OutlierHandler. - Learned statistics must come from training data only. Applying
fiton the full dataset before splitting is leakage. - Edge cases. All-NaN columns (mean is undefined), mode ties (pick deterministically), and unseen columns at transform time need explicit handling.
- Hygiene. Bare
except:clauses, non-PEP 8 names, no docstrings, no tests. Add tests analogous to the one above: fill values come from training data and the input is not modified.
Common mistakes in answers: describing the script without explaining why strict mode matters, saying the split is "just for style" rather than leakage and serving, and proposing a test that only checks the happy path.