Session Conversion Prediction Pipeline
Medium · Machine Learning · Machine Learning Engineer · Online Assessment
Problem Statement
Implement a leak-free tabular classification pipeline in Python and NumPy that cleans noisy browsing-session records, filters out low-signal columns, engineers numeric and categorical features, fits an L2-regularized logistic classifier, selects an optimal probability cutoff for support-weighted F1, and exports binary id,outcome predictions.
Raw CSV tables map column names to semantic domain types defined by:
NUMERIC_KINDS = ("count", "duration", "rate", "score")CATEGORICAL_KINDS = ("flag", "category")MISSING_TOKENS = {"", "na", "n/a", "nan", "null", "none", "?", "-"}
Implement the following functions and class (preserving the signatures in starter.py):
parse_number(value: Any) -> Optional[float]- Strip surrounding whitespace if
valueis a string and returnNonewhen the lowercased string is inMISSING_TOKENS. - Convert
valuetofloat, returningNoneifvalueisNone, cannot be parsed, or producesNaNor+/-inf. Normalize-0.0to+0.0.
- Strip surrounding whitespace if
clean_value(value: Any, kind: str) -> Optional[float]- Parse
valuewithparse_numberand validate domain bounds:"count"and"category": whole numbers>= 0(x >= 0andx == floor(x))."duration": any finite number>= 0."rate": any finite number in[0.0, 1.0]."flag":0.0or1.0."score": any finite float.
- Return
Nonewhen validation fails, and raiseValueErrorfor an unrecognizedkind.
- Parse
clean_rows(rows: List[Dict[str, Any]], schema: Dict[str, str]) -> List[Dict[str, Optional[float]]]- Return one cleaned dictionary per input row containing
clean_value(row.get(col), kind)for every(col, kind)inschema.
- Return one cleaned dictionary per input row containing
columns_to_drop(rows: List[Dict[str, Optional[float]]], columns: Sequence[str], max_missing: float = 0.5) -> List[str]- Return columns (in their input order) whose
Nonecount strictly exceedsmax_missing * len(rows)or that contain at most1distinct non-Nonevalue.
- Return columns (in their input order) whose
Preprocessor(numeric: Sequence[str], categorical: Sequence[str])fit(rows)learns statistics strictly from training rows and populatesself.feature_names:- Each numeric column
colemits[col, f"{col}__missing"]: imputeNonewith the median of present values incol(0.0if all values areNone), compute the population mean and population standard deviation (np.std, using1.0whenstd == 0.0) on the median-filled training column, and set the missing indicator to1.0iff the input cell wasNone. - Each categorical column
colemits one0.0/1.0indicator per sorted distinct non-Nonetraining value namedf"{col}={level:g}", followed byf"{col}=missing". Any test level unseen duringfitmaps to all zeros across that column's indicators.
- Each numeric column
transform(rows)returns afloatNumPy matrix of shape(len(rows), len(self.feature_names)).
train_logistic_regression(X: np.ndarray, y: np.ndarray, l2: float = 1e-3, learning_rate: float = 0.5, epochs: int = 500) -> Tuple[np.ndarray, float]- Starting from zero weights
wand zero interceptb(returning immediately ifXhas0rows), runepochssteps of full-batch gradient descent minimizing mean binary cross-entropy loss plus(l2 / 2) * ||w||^2(do not regularizeb), usingsigmoidclipped to[-35.0, 35.0].
- Starting from zero weights
weighted_f1(y_true: Sequence[int], y_pred: Sequence[int]) -> float- Return the support-weighted mean of the binary Class
1F1 score and Class0F1 score (0.0on empty input, and0.0for a class when2 * TP + FP + FN == 0).
- Return the support-weighted mean of the binary Class
best_threshold(y_true: Sequence[int], probs: Sequence[float]) -> Tuple[float, float]- Among candidate cutoffs
ttaken fromprobsunder the rulepredict 1 iff prob >= t, return(best_t, best_weighted_f1). Break ties in score by choosing the largest thresholdt. RaiseValueErrorifprobsis empty orlen(y_true) != len(probs).
- Among candidate cutoffs
stratified_split(y: Sequence[int], val_fraction: float = 0.2, seed: int = 0) -> Tuple[List[int], List[int]]- Using
random.Random(seed), iteratelabelin(0, 1), shuffle the indices wherey[i] == label, place the firstround(count * val_fraction)indices into validation and the remainder into training, and return(sorted(train_idx), sorted(val_idx)).
- Using
build_submission(train_rows, test_rows, schema, id_column="id", target="outcome", val_fraction=0.2, seed=0) -> Dict[str, Any]andwrite_submission(path, submission) -> None- Keep only training rows whose
targetcleans to0.0or1.0as"flag"(counting skipped training rows in"unlabelled_rows"). - Clean features, select
"dropped"columns from cleaned labelled training rows only, tune("threshold", "val_weighted_f1")using a model trained on the stratified training fold and evaluated on the validation fold, then refitPreprocessorand logistic regression on all labelled training rows to classifytest_rowsin order as[(row[id_column], int(prob >= threshold)), ...]. write_submissionwrites a CSV file with headerid,outcomefollowed by each pair.
- Keep only training rows whose
Examples
Example 1
Input:
schema = {
"views": "count",
"bounce": "rate",
"constant_col": "flag",
"sparse_col": "score",
"channel": "category",
}
raw_train = [
{"views": "2", "bounce": "0.25", "constant_col": "1", "sparse_col": "NA", "channel": "10"},
{"views": "6", "bounce": "1.4", "constant_col": "1", "sparse_col": "", "channel": "20"},
{"views": "-3", "bounce": "0.50", "constant_col": "?", "sparse_col": "1.2", "channel": "10"},
{"views": "10", "bounce": "0.75", "constant_col": "1", "sparse_col": "null", "channel": "?"},
]
Output:
columns_to_drop(clean_rows(raw_train, schema), list(schema))->["constant_col", "sparse_col"]- Fitting
Preprocessor(["views"], ["channel"])on the cleaned rows producesfeature_names = ["views", "views__missing", "channel=10", "channel=20", "channel=missing"], and transforming[{"views": 12.0, "channel": 99.0}, {"views": None, "channel": 20.0}]yields:[[2.12132034, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 1.0, 0.0]]
Explanation: "1.4" (rate above 1) and "-3" (negative count) become None. "constant_col" has only one distinct non-missing value (1.0), and "sparse_col" is missing in 3 of 4 rows (75% > 50%), so both are dropped. Present "views" values [2, 6, 10] have median 6.0; filling row 2 gives [2, 6, 6, 10] with mean 6.0 and population std sqrt(8) ≈ 2.828427. Unseen category 99.0 produces all zeros in the "channel" indicators.
Example 2
Input:
y_true = [1, 0, 1, 0, 0, 0]
probs = [0.92, 0.65, 0.35, 0.28, 0.15, 0.05]
Output:
best_threshold(y_true, probs)->(0.35, 0.8380952380952381)(88 / 105)
Explanation: With 2 positives and 4 negatives, a default 0.50 cutoff predicts [1, 1, 0, 0, 0, 0] for a weighted F1 of (2 * 0.5 + 4 * 0.75) / 6 = 2/3 ≈ 0.6667. Lowering the cutoff to 0.35 predicts [1, 1, 1, 0, 0, 0] (TP=2, FP=1, FN=0, TN=3), raising Class 1 F1 to 4/5 and Class 0 F1 to 6/7 for (2 * 4/5 + 4 * 6/7) / 6 = 88/105 ≈ 0.8381.
Constraints
- Labels in valid training rows are binary integers (
0or1); test rows carry no target column. - Column dropping uses a strict inequality (
missing_count > max_missing * len(rows)), so a column missing in exactly50%of training rows is retained whenmax_missing = 0.5(provided it has at least2distinct non-missing values). - All preprocessing statistics and column-drop decisions must be derived strictly from training rows without inspecting validation or test features.
best_thresholdmust run inO(n log n)time so validation splits with tens of thousands of rows finish well under a second.
Step-by-step walkthrough
Understand the goal, metric, and schema contract
We receive a labelled training CSV (
outcomein{0, 1}) and an unlabelled test CSV carrying session attributes plusid. Our pipeline must produceid,outcomebinary predictions evaluated by support-weighted F1 — the average of Class 1's F1 score and Class 0's F1 score weighted by each class's true row count.Before coding, lock down three modeling contracts in a schema dictionary:
- Domain validation over ad-hoc row deletion: Impossible entries — negative counts or durations, rates outside
[0, 1], non-binary flags, fractional or negative category codes, or corrupted strings like"error"— map cleanly toNoneso one unified imputer handles both blank cells and out-of-range corruption without discarding valid columns in the same row. - Nominal integer categories: Integer-coded columns such as
user_deviceortraffic_typerepresent unordered labels rather than magnitudes, so we expand them into one-hot0/1indicators instead of feeding raw integers into linear weights. - Validation design: Train an L2-regularized logistic regression baseline and tune the decision threshold on a stratified holdout split that preserves the exact positive-to-negative class ratio.
MISSING_TOKENS = {"", "na", "n/a", "nan", "null", "none", "?", "-"} NUMERIC_KINDS = ("count", "duration", "rate", "score") CATEGORICAL_KINDS = ("flag", "category") # Placeholder column schema mapping column_name -> semantic domain kind. EXAMPLE_SCHEMA = { "page_count": "count", "time_spent": "duration", "exit_rate": "rate", "dropoff_rate": "rate", "engagement_score": "score", "promotion": "flag", "holiday": "flag", "user_device": "category", "traffic_type": "category", }- Domain validation over ad-hoc row deletion: Impossible entries — negative counts or durations, rates outside
Clean raw CSV cells and turn impossible values into missing
csv.DictReaderyields every cell as a string, where missing or corrupted entries show up as"","NA","?","error","-1", or"1.7"in a[0, 1]rate column. Split cleaning into two focused helpers:parse_number(value)strips whitespace, rejects missing-value tokens, junk strings,NaN, and+/-inf, and normalizes-0.0to+0.0(so formatting category0.0with:gnever produces"-0").clean_value(value, kind)checks domain validity (countandcategorymust be whole numbers>= 0;duration >= 0;ratein[0, 1];flagin{0, 1};scoreany finite float) and returnsNonewhenever a cell violates its domain.
def parse_number(value: Any) -> Optional[float]: """Return a finite float, or None for missing tokens, junk text, NaN and infinity.""" if value is None: return None if isinstance(value, str): text = value.strip() if text.lower() in MISSING_TOKENS: return None try: number = float(text) except ValueError: return None else: try: number = float(value) except (TypeError, ValueError): return None # Reject NaN and +/-inf, and normalize -0.0 to +0.0 so string formatting stays "0", not "-0". if not math.isfinite(number): return None if number == 0.0: return 0.0 return number def clean_value(value: Any, kind: str) -> Optional[float]: """Return the parsed value if it is valid for its kind, else None (treated as missing). count / category: a whole number >= 0; duration: >= 0; rate: in [0, 1]; flag: 0 or 1; score: any finite number. """ number = parse_number(value) if number is None: return None # Convert domain bugs (e.g. negative counts or rates > 1.0) into None so imputation handles them. if kind in ("count", "category"): is_valid = number >= 0.0 and number == math.floor(number) elif kind == "duration": is_valid = number >= 0.0 elif kind == "rate": is_valid = 0.0 <= number <= 1.0 elif kind == "flag": is_valid = number == 0.0 or number == 1.0 elif kind == "score": is_valid = True else: raise ValueError(f"unknown column kind: {kind!r}") return number if is_valid else None def clean_rows(rows: List[Dict[str, Any]], schema: Dict[str, str]) -> List[Dict[str, Optional[float]]]: """Return one dict per row holding every schema column cleaned by clean_value.""" cleaned_rows: List[Dict[str, Optional[float]]] = [] for raw_row in rows: cleaned_row: Dict[str, Optional[float]] = {} for column, kind in schema.items(): cleaned_row[column] = clean_value(raw_row.get(column), kind) cleaned_rows.append(cleaned_row) return cleaned_rowsDrop sparse and zero-variance columns using training data only
Any column whose missing fraction strictly exceeds
max_missing(0.5) or that exhibits at most one distinct non-missing value adds noise without predictive signal. Three subtle details keep this step exact:- Run
columns_to_dropafterclean_rows: A rate column holding"1.4"in 3 of 4 rows looks populated as raw strings, yet turns into 75%Noneafter domain validation and gets dropped. - Strict
>comparison: Exceeding50%means 5 missing out of 10 rows (50%) is retained, whereas 6 out of 10 (60%) is dropped (missing_count > max_missing * total_rows). - At most 1 distinct present value (
distinct_count <= 1): Eliminates both constant flags (likeconstant_col = 1everywhere) and 100%-empty columns. Compute this list strictly on labelled training rows so test-set distributions never leak into feature selection.
def columns_to_drop(rows: List[Dict[str, Optional[float]]], columns: Sequence[str], max_missing: float = 0.5) -> List[str]: """Columns, in the given order, whose missing share is above max_missing or that have at most one distinct non-missing value.""" total_rows = len(rows) dropped_columns: List[str] = [] for column in columns: present_values: List[float] = [] for row in rows: val = row.get(column) if val is not None: present_values.append(val) missing_count = total_rows - len(present_values) distinct_count = len(set(present_values)) # Strict '>' keeps columns with exact 50% missing; '<= 1' drops constant or all-missing columns. if missing_count > max_missing * total_rows or distinct_count <= 1: dropped_columns.append(column) return dropped_columns- Run
Impute, scale, and one-hot encode without data leakage
Data leakage in preprocessing happens whenever medians, means, standard deviations, or category vocabularies are computed across validation or test rows. Encapsulate every learned statistic inside
Preprocessor.fit(train_rows), and apply those frozen training statistics insidePreprocessor.transform(any_rows):- Numeric column
colexpands into two features[col, col__missing]: fillNonewith the training median (unlike the mean, a median is not pulled around by extreme outlier sessions), setcol__missing = 1.0whenNone(since "missingness" itself can predict drop-off!), and z-score standardize(value - train_mean) / train_stdso gradient descent converges smoothly (train_std == 0falls back to1.0). - Categorical column
colexpands into one0/1indicator per sorted level seen in training (col=1,col=2, ...) pluscol=missing. Iftest.csvcontains a brand-new category code (likedevice = 9), every indicator stays0.0instead of crashing.
Here is how Example 1's retained slice (
viewsnumeric with cleaned values[2.0, 6.0, None, 10.0],channelcategorical with training levels[10, 20]) transforms two new rows into a 5-column matrix:Train fit stats: views median = 6.0, filled = [2, 6, 6, 10], mean = 6.0, std = sqrt(8) = 2.828; channel levels = [10, 20] Input row views (z-score) views__missing channel=10 channel=20 channel=missing ---------------------------------- ----------------- -------------- ---------- ---------- --------------- {"views": 12.0, "channel": 99.0} (12.0-6.0)/2.828 0.0 0.0 0.0 0.0 <- unseen level 99! {"views": None, "channel": 20.0} (6.0-6.0)/2.828 1.0 0.0 1.0 0.0class Preprocessor: """Learn imputation, scaling and category levels from training rows only. Numeric column -> [column, column + "__missing"]: fill missing values with the train median, standardize with the train mean and std of the filled column (std 0 -> 1), and set the flag to 1.0 where the value was missing. Categorical column -> one indicator per level seen in train (sorted), named f"{column}={level:g}", then f"{column}=missing". A level never seen in train gets all zeros. """ def __init__(self, numeric: Sequence[str], categorical: Sequence[str]) -> None: self.numeric = list(numeric) self.categorical = list(categorical) # Numeric stats keyed by column name, e.g. {"page_count": 3.0} self.medians: Dict[str, float] = {} self.means: Dict[str, float] = {} self.stds: Dict[str, float] = {} # Categorical levels keyed by column name, e.g. {"device": [1.0, 2.0]} self.levels: Dict[str, List[float]] = {} # Fast O(1) lookup from category code -> offset inside that column's one-hot slice self.level_to_offset: Dict[str, Dict[float, int]] = {} self.feature_names: List[str] = [] def fit(self, rows: List[Dict[str, Optional[float]]]) -> "Preprocessor": self.feature_names = [] # Phase 1: Learn median imputation and post-imputation z-score stats on training rows. for column in self.numeric: present_values = [row.get(column) for row in rows if row.get(column) is not None] median_val = float(np.median(present_values)) if present_values else 0.0 filled_values = [ median_val if row.get(column) is None else float(row[column]) # type: ignore[arg-type] for row in rows ] std_val = float(np.std(filled_values)) self.medians[column] = median_val self.means[column] = float(np.mean(filled_values)) # Guard against division by zero if a numeric feature is constant within a split. self.stds[column] = std_val if std_val > 0.0 else 1.0 self.feature_names.append(column) self.feature_names.append(f"{column}__missing") # Phase 2: Record sorted training categories plus one trailing '=missing' slot per column. for column in self.categorical: seen_levels = sorted({ float(row[column]) # type: ignore[arg-type] for row in rows if row.get(column) is not None }) self.levels[column] = seen_levels self.level_to_offset[column] = { level: offset for offset, level in enumerate(seen_levels) } for level in seen_levels: self.feature_names.append(f"{column}={level:g}") self.feature_names.append(f"{column}=missing") return self def transform(self, rows: List[Dict[str, Optional[float]]]) -> np.ndarray: # Output matrix shape: (num_rows, num_engineered_features), initialized to 0.0. X = np.zeros((len(rows), len(self.feature_names)), dtype=float) for row_idx, row in enumerate(rows): col_cursor = 0 # Emit [standardized_value, missing_indicator] for each numeric column. for column in self.numeric: raw_val = row.get(column) if raw_val is None: filled_val = self.medians[column] X[row_idx, col_cursor + 1] = 1.0 else: filled_val = raw_val X[row_idx, col_cursor] = (filled_val - self.means[column]) / self.stds[column] col_cursor += 2 # Emit one-hot indicator for known levels or '=missing'; unseen test levels stay all-zero. for column in self.categorical: levels = self.levels[column] offset_map = self.level_to_offset[column] raw_val = row.get(column) if raw_val is None: X[row_idx, col_cursor + len(levels)] = 1.0 elif raw_val in offset_map: X[row_idx, col_cursor + offset_map[raw_val]] = 1.0 col_cursor += len(levels) + 1 return X- Numeric column
Train a regularized logistic regression baseline
Logistic regression predicts purchase probability by passing a linear score
z = X @ w + bthrough the sigmoid curve1 / (1 + exp(-z)), squashing any real number smoothly into(0, 1). We find weightswand biasbby minimizing average binary cross-entropy (log loss) plus an L2 regularization penalty(l2 / 2) * ||w||^2(which shrinks noisy feature weights toward zero to prevent overfitting, while leaving the interceptbunpenalized so the model matches the base purchase rate freely).Because standardized features keep curvature well-behaved and the objective is strictly convex (shaped like one smooth bowl with a single global minimum), full-batch gradient descent updates
(w, b)cleanly each epoch:probs = sigmoid(X @ w + b) # predicted probabilities in (0, 1), shape (n,) error = probs - y # prediction residual, shape (n,) grad_w = (X.T @ error) / n + l2 * w # slope wrt feature weights, shape (d,) grad_b = mean(error) # slope wrt scalar biasClipping
zto[-35, 35]insidesigmoidpreventsnp.exp(-z)from overflowingfloat64whenzis very negative, while changing probabilities by less than1e-15.def sigmoid(z: np.ndarray) -> np.ndarray: # Clip logits to [-35, 35] to prevent exp() overflow while keeping precision within ~1e-15. clipped = np.clip(z, -35.0, 35.0) return 1.0 / (1.0 + np.exp(-clipped)) def train_logistic_regression(X: np.ndarray, y: np.ndarray, l2: float = 1e-3, learning_rate: float = 0.5, epochs: int = 500) -> Tuple[np.ndarray, float]: """Return (w, b) minimizing mean log loss + (l2 / 2) * |w|^2 by full-batch gradient descent.""" num_samples, num_features = X.shape weights = np.zeros(num_features, dtype=float) bias = 0.0 if num_samples == 0: return weights, bias for _ in range(epochs): probs = sigmoid(X @ weights + bias) error = probs - y # Regularize feature weights w with L2, leaving intercept b unpenalized to match base rate. grad_w = (X.T @ error) / num_samples + l2 * weights grad_b = float(np.mean(error)) weights -= learning_rate * grad_w bias -= learning_rate * grad_b return weights, bias def predict_proba(X: np.ndarray, w: np.ndarray, b: float) -> np.ndarray: return sigmoid(X @ w + b)Compute weighted F1 for both buyers and non-buyers
For a single class, the F1 score is the harmonic mean of precision and recall (
2 * P * R / (P + R)), which simplifies directly in terms of confusion-matrix counts to2 * TP / (2 * TP + FP + FN)(defined as0.0when2 * TP + FP + FN == 0).Weighted F1 computes F1 separately for Class 1 (buyers) and Class 0 (non-buyers), then averages them weighted by each class's true row count (support): - Class 1 (
outcome == 1): uses(tp, fp, fn)withsupport_1 = tp + fn. - Class 0 (outcome == 0): treats "no purchase" as the target class, sotnplays the role of true positives,fnacts as false positives (predicted0when truth was1), andfpacts as false negatives (predicted1when truth was0), withsupport_0 = tn + fp.Notice what this means when
85%of sessions are non-buyers:85%of weighted F1 comes from Class 0! Predicting0for every row already scores0.85 * (2 * 0.85) / (2 * 0.85 + 0.15) ≈ 0.78, so tuning the probability cutoff is essential to beat that baseline.def f1_from_counts(tp: int, fp: int, fn: int) -> float: """F1 of one class as 2TP / (2TP + FP + FN); 0.0 when the class has no true positive.""" denominator = 2 * tp + fp + fn if denominator == 0: return 0.0 return (2.0 * tp) / denominator def weighted_f1_from_counts(tp: int, fp: int, fn: int, tn: int) -> float: """Binary weighted F1: F1 of class 1 and F1 of class 0, weighted by each class's true count.""" f1_positive = f1_from_counts(tp, fp, fn) # For class 0 ("no purchase"), true negatives act as TP and false negatives/positives swap roles. f1_negative = f1_from_counts(tn, fn, fp) support_positive = tp + fn support_negative = tn + fp total_support = support_positive + support_negative if total_support == 0: return 0.0 return (support_positive * f1_positive + support_negative * f1_negative) / total_support def weighted_f1(y_true: Sequence[int], y_pred: Sequence[int]) -> float: """Support-weighted mean of the per-class F1 scores for 0/1 labels (0.0 for empty input).""" tp = fp = fn = tn = 0 for truth, pred in zip(y_true, y_pred): if truth == 1 and pred == 1: tp += 1 elif truth == 0 and pred == 1: fp += 1 elif truth == 1 and pred == 0: fn += 1 else: tn += 1 return weighted_f1_from_counts(tp, fp, fn, tn)Find the optimal threshold in O(n log n) with a sorted sweep
Checking every distinct predicted probability
tby recomputing allnpredictions from scratch takesO(n^2)time. Instead, sort(prob, label)pairs once from highest probability down to lowest:- As we lower
candidate_tto the next distinct probability, every row equal tocandidate_tflips from predicted0to predicted1(because our rule isprob >= candidate_t, tied rows must cross together in an innerwhileloop!). - Each row updates
tporfponce inO(1)time, whilefn = total_positive - tpandtn = total_negative - fp. - Because we sweep from largest threshold to smallest, updating
best_tonly whenscore > best_score + 1e-12guarantees ties go to the larger threshold — even when two algebraically identical fractions (like(6 * 1/2 + 3 * 3/5) / 9and(6 * 4/5) / 9, both8/15) differ in the 16th decimal place due to floating-point rounding!
Trace this descending sweep on Example 2's 6 validation rows (
y_true = [1, 0, 1, 0, 0, 0],probs = [0.92, 0.65, 0.35, 0.28, 0.15, 0.05],total_pos = 2,total_neg = 4):candidate_t Rows with prob >= t TP FP FN TN F1(cls 1) F1(cls 0) Weighted F1 ----------- -------------------------- -- -- -- -- --------- --------- ------------------------ 0.92 {0.92} 1 0 1 4 2/3=.667 8/9=.889 (2*.667 + 4*.889)/6 = .815 0.65 {0.92, 0.65} 1 1 1 3 2/4=.500 6/8=.750 (2*.500 + 4*.750)/6 = .667 <- default 0.5! 0.35 {0.92, 0.65, 0.35} 2 1 0 3 4/5=.800 6/7=.857 (2*.800 + 4*.857)/6 = .838 <- BEST (88/105)! 0.28 {0.92, 0.65, 0.35, 0.28} 2 2 0 2 4/6=.667 4/6=.667 (2*.667 + 4*.667)/6 = .667 0.15 {0.92..0.15} 2 3 0 1 4/7=.571 2/5=.400 (2*.571 + 4*.400)/6 = .457 0.05 all 6 rows 2 4 0 0 4/8=.500 0/4=.000 (2*.500 + 4*.000)/6 = .167The sweep selects
threshold = 0.35(88/105 ≈ 0.838), beating the naive0.50cutoff (2/3 ≈ 0.667) by+0.171!def best_threshold(y_true: Sequence[int], probs: Sequence[float]) -> Tuple[float, float]: """Return (threshold, score): the predicted probability t that maximizes the weighted F1 of "predict 1 when prob >= t". Ties go to the larger threshold. Raise ValueError on empty input.""" if len(probs) == 0 or len(y_true) != len(probs): raise ValueError("y_true and probs must be non-empty sequences of equal length") # Sort (prob, label) from highest to lowest probability so each group crosses 'prob >= t' once. sorted_pairs = sorted(zip(probs, y_true), key=lambda pair: pair[0], reverse=True) total_positive = sum(y_true) total_negative = len(sorted_pairs) - total_positive tp = 0 fp = 0 best_t = float(sorted_pairs[0][0]) best_score = -1.0 idx = 0 num_rows = len(sorted_pairs) while idx < num_rows: candidate_t = sorted_pairs[idx][0] # Admit all rows tied at candidate_t together, because 'prob >= candidate_t' includes them all. while idx < num_rows and sorted_pairs[idx][0] == candidate_t: if sorted_pairs[idx][1] == 1: tp += 1 else: fp += 1 idx += 1 fn = total_positive - tp tn = total_negative - fp score = weighted_f1_from_counts(tp, fp, fn, tn) # Scanning high-to-low + 1e-12 float tolerance ensures exact ties keep the larger threshold. if score > best_score + 1e-12: best_t = float(candidate_t) best_score = score return best_t, best_score- As we lower
Assemble the leak-free validation and submission pipeline
Now wire everything together cleanly inside
build_submissionso zero information leaks from validation or test rows into training:train_rows ---> filter valid 0/1 target ---> clean_rows ---> columns_to_drop (from train ONLY!) | +-------------------------+-------------------------+ v (80% stratified fit_rows) v (100% train_clean) Preprocessor.fit + LogReg Refit Preprocessor + LogReg | | v (transform 20% val_rows) v (transform test_clean) best_threshold(val_labels, val_probs) ------------> int(test_prob >= threshold)- Filter target bugs: Skip training rows whose
outcomeis missing or corrupted (like"?"), recording their count inunlabelled_rows. - Clean and drop columns on
train_cleanonly: Never inspecttest_rowswhen decidingdropped. - Stratified validation tuning:
stratified_splitshuffles Class0and Class1separately so bothfit_rows(80%) andval_rows(20%) keep the exact same purchase rate. FitPreprocessorand logistic regression strictly onfit_rows, then pickthresholdonval_rows. - Final refit & CSV export: Refit
Preprocessorand logistic regression on 100% oftrain_cleanto use all labeled data, scoretest_cleanwiththreshold, and writeid,outcomein original test order.
def stratified_split(y: Sequence[int], val_fraction: float = 0.2, seed: int = 0) -> Tuple[List[int], List[int]]: """Return sorted (train, val) index lists; each class sends round(count * val_fraction) rows to val.""" rng = random.Random(seed) train_indices: List[int] = [] val_indices: List[int] = [] # Split class 0 and class 1 independently so both partitions preserve the exact purchase ratio. for label in (0, 1): class_indices = [idx for idx, target_val in enumerate(y) if target_val == label] rng.shuffle(class_indices) val_count = round(len(class_indices) * val_fraction) val_indices.extend(class_indices[:val_count]) train_indices.extend(class_indices[val_count:]) return sorted(train_indices), sorted(val_indices) def fit_model(rows: List[Dict[str, Optional[float]]], y: np.ndarray, numeric: List[str], categorical: List[str]) -> Tuple[Preprocessor, np.ndarray, float]: """Fit a fresh Preprocessor and regularized logistic regression model on the given rows.""" preprocessor = Preprocessor(numeric, categorical).fit(rows) X_matrix = preprocessor.transform(rows) weights, bias = train_logistic_regression(X_matrix, y) return preprocessor, weights, bias def build_submission(train_rows: List[Dict[str, Any]], test_rows: List[Dict[str, Any]], schema: Dict[str, str], id_column: str = "id", target: str = "outcome", val_fraction: float = 0.2, seed: int = 0) -> Dict[str, Any]: """Clean, drop bad columns, tune the threshold on a stratified validation split, refit on all labelled rows and predict the test rows. Return {"unlabelled_rows", "dropped", "threshold", "val_weighted_f1", "submission"}, where submission is a list of (id, 0 or 1) in test-row order. """ # Phase 1: Keep only training rows whose target parses cleanly as 0 or 1. labelled_rows: List[Dict[str, Any]] = [] labels: List[int] = [] for row in train_rows: parsed_label = clean_value(row.get(target), "flag") if parsed_label is not None: labelled_rows.append(row) labels.append(int(parsed_label)) y_all = np.array(labels, dtype=float) # Phase 2: Clean features and choose dropped columns strictly from training data (no test leakage). train_clean = clean_rows(labelled_rows, schema) test_clean = clean_rows(test_rows, schema) dropped = columns_to_drop(train_clean, list(schema)) numeric_cols: List[str] = [] categorical_cols: List[str] = [] for column, kind in schema.items(): if column in dropped: continue if kind in NUMERIC_KINDS: numeric_cols.append(column) else: categorical_cols.append(column) # Phase 3: Fit Preprocessor + model on fit_rows ONLY, then tune threshold on held-out val_rows. fit_idx, val_idx = stratified_split(labels, val_fraction, seed) fit_rows = [train_clean[i] for i in fit_idx] val_rows = [train_clean[i] for i in val_idx] val_labels = [labels[i] for i in val_idx] val_prep, val_w, val_b = fit_model(fit_rows, y_all[fit_idx], numeric_cols, categorical_cols) val_probs = predict_proba(val_prep.transform(val_rows), val_w, val_b) threshold, val_score = best_threshold(val_labels, val_probs) # Phase 4: Refit on 100% of labelled training rows and generate binary test predictions. full_prep, full_w, full_b = fit_model(train_clean, y_all, numeric_cols, categorical_cols) test_probs = predict_proba(full_prep.transform(test_clean), full_w, full_b) submission: List[Tuple[Any, int]] = [] for raw_test_row, prob in zip(test_rows, test_probs): predicted_label = int(prob >= threshold) submission.append((raw_test_row[id_column], predicted_label)) return { "unlabelled_rows": len(train_rows) - len(labelled_rows), "dropped": dropped, "threshold": threshold, "val_weighted_f1": val_score, "submission": submission, }- Filter target bugs: Skip training rows whose
Complete solution
from typing import Any, Dict, List, Optional, Sequence, Tuple import csv import math import random import numpy as np # Lowercase text placeholders commonly found in messy CSV exports for missing cells. MISSING_TOKENS = {"", "na", "n/a", "nan", "null", "none", "?", "-"} NUMERIC_KINDS = ("count", "duration", "rate", "score") CATEGORICAL_KINDS = ("flag", "category") # Placeholder column schema mapping column_name -> semantic domain kind. EXAMPLE_SCHEMA = { "page_count": "count", "time_spent": "duration", "exit_rate": "rate", "dropoff_rate": "rate", "engagement_score": "score", "promotion": "flag", "holiday": "flag", "user_device": "category", "traffic_type": "category", } def parse_number(value: Any) -> Optional[float]: """Return a finite float, or None for missing tokens, junk text, NaN and infinity.""" if value is None: return None if isinstance(value, str): text = value.strip() if text.lower() in MISSING_TOKENS: return None try: number = float(text) except ValueError: return None else: try: number = float(value) except (TypeError, ValueError): return None # Reject NaN and +/-inf, and normalize -0.0 to +0.0 so string formatting stays "0", not "-0". if not math.isfinite(number): return None if number == 0.0: return 0.0 return number def clean_value(value: Any, kind: str) -> Optional[float]: """Return the parsed value if it is valid for its kind, else None (treated as missing). count / category: a whole number >= 0; duration: >= 0; rate: in [0, 1]; flag: 0 or 1; score: any finite number. """ number = parse_number(value) if number is None: return None # Convert domain bugs (e.g. negative counts or rates > 1.0) into None so imputation handles them. if kind in ("count", "category"): is_valid = number >= 0.0 and number == math.floor(number) elif kind == "duration": is_valid = number >= 0.0 elif kind == "rate": is_valid = 0.0 <= number <= 1.0 elif kind == "flag": is_valid = number == 0.0 or number == 1.0 elif kind == "score": is_valid = True else: raise ValueError(f"unknown column kind: {kind!r}") return number if is_valid else None def clean_rows(rows: List[Dict[str, Any]], schema: Dict[str, str]) -> List[Dict[str, Optional[float]]]: """Return one dict per row holding every schema column cleaned by clean_value.""" cleaned_rows: List[Dict[str, Optional[float]]] = [] for raw_row in rows: cleaned_row: Dict[str, Optional[float]] = {} for column, kind in schema.items(): cleaned_row[column] = clean_value(raw_row.get(column), kind) cleaned_rows.append(cleaned_row) return cleaned_rows def columns_to_drop(rows: List[Dict[str, Optional[float]]], columns: Sequence[str], max_missing: float = 0.5) -> List[str]: """Columns, in the given order, whose missing share is above max_missing or that have at most one distinct non-missing value.""" total_rows = len(rows) dropped_columns: List[str] = [] for column in columns: present_values: List[float] = [] for row in rows: val = row.get(column) if val is not None: present_values.append(val) missing_count = total_rows - len(present_values) distinct_count = len(set(present_values)) # Strict '>' keeps columns with exact 50% missing; '<= 1' drops constant or all-missing columns. if missing_count > max_missing * total_rows or distinct_count <= 1: dropped_columns.append(column) return dropped_columns class Preprocessor: """Learn imputation, scaling and category levels from training rows only. Numeric column -> [column, column + "__missing"]: fill missing values with the train median, standardize with the train mean and std of the filled column (std 0 -> 1), and set the flag to 1.0 where the value was missing. Categorical column -> one indicator per level seen in train (sorted), named f"{column}={level:g}", then f"{column}=missing". A level never seen in train gets all zeros. """ def __init__(self, numeric: Sequence[str], categorical: Sequence[str]) -> None: self.numeric = list(numeric) self.categorical = list(categorical) # Numeric stats keyed by column name, e.g. {"page_count": 3.0} self.medians: Dict[str, float] = {} self.means: Dict[str, float] = {} self.stds: Dict[str, float] = {} # Categorical levels keyed by column name, e.g. {"device": [1.0, 2.0]} self.levels: Dict[str, List[float]] = {} # Fast O(1) lookup from category code -> offset inside that column's one-hot slice self.level_to_offset: Dict[str, Dict[float, int]] = {} self.feature_names: List[str] = [] def fit(self, rows: List[Dict[str, Optional[float]]]) -> "Preprocessor": self.feature_names = [] # Phase 1: Learn median imputation and post-imputation z-score stats on training rows. for column in self.numeric: present_values = [row.get(column) for row in rows if row.get(column) is not None] median_val = float(np.median(present_values)) if present_values else 0.0 filled_values = [ median_val if row.get(column) is None else float(row[column]) # type: ignore[arg-type] for row in rows ] std_val = float(np.std(filled_values)) self.medians[column] = median_val self.means[column] = float(np.mean(filled_values)) # Guard against division by zero if a numeric feature is constant within a split. self.stds[column] = std_val if std_val > 0.0 else 1.0 self.feature_names.append(column) self.feature_names.append(f"{column}__missing") # Phase 2: Record sorted training categories plus one trailing '=missing' slot per column. for column in self.categorical: seen_levels = sorted({ float(row[column]) # type: ignore[arg-type] for row in rows if row.get(column) is not None }) self.levels[column] = seen_levels self.level_to_offset[column] = { level: offset for offset, level in enumerate(seen_levels) } for level in seen_levels: self.feature_names.append(f"{column}={level:g}") self.feature_names.append(f"{column}=missing") return self def transform(self, rows: List[Dict[str, Optional[float]]]) -> np.ndarray: # Output matrix shape: (num_rows, num_engineered_features), initialized to 0.0. X = np.zeros((len(rows), len(self.feature_names)), dtype=float) for row_idx, row in enumerate(rows): col_cursor = 0 # Emit [standardized_value, missing_indicator] for each numeric column. for column in self.numeric: raw_val = row.get(column) if raw_val is None: filled_val = self.medians[column] X[row_idx, col_cursor + 1] = 1.0 else: filled_val = raw_val X[row_idx, col_cursor] = (filled_val - self.means[column]) / self.stds[column] col_cursor += 2 # Emit one-hot indicator for known levels or '=missing'; unseen test levels stay all-zero. for column in self.categorical: levels = self.levels[column] offset_map = self.level_to_offset[column] raw_val = row.get(column) if raw_val is None: X[row_idx, col_cursor + len(levels)] = 1.0 elif raw_val in offset_map: X[row_idx, col_cursor + offset_map[raw_val]] = 1.0 col_cursor += len(levels) + 1 return X def sigmoid(z: np.ndarray) -> np.ndarray: # Clip logits to [-35, 35] to prevent exp() overflow while keeping precision within ~1e-15. clipped = np.clip(z, -35.0, 35.0) return 1.0 / (1.0 + np.exp(-clipped)) def train_logistic_regression(X: np.ndarray, y: np.ndarray, l2: float = 1e-3, learning_rate: float = 0.5, epochs: int = 500) -> Tuple[np.ndarray, float]: """Return (w, b) minimizing mean log loss + (l2 / 2) * |w|^2 by full-batch gradient descent.""" num_samples, num_features = X.shape weights = np.zeros(num_features, dtype=float) bias = 0.0 if num_samples == 0: return weights, bias for _ in range(epochs): probs = sigmoid(X @ weights + bias) error = probs - y # Regularize feature weights w with L2, leaving intercept b unpenalized to match base rate. grad_w = (X.T @ error) / num_samples + l2 * weights grad_b = float(np.mean(error)) weights -= learning_rate * grad_w bias -= learning_rate * grad_b return weights, bias def predict_proba(X: np.ndarray, w: np.ndarray, b: float) -> np.ndarray: return sigmoid(X @ w + b) def f1_from_counts(tp: int, fp: int, fn: int) -> float: """F1 of one class as 2TP / (2TP + FP + FN); 0.0 when the class has no true positive.""" denominator = 2 * tp + fp + fn if denominator == 0: return 0.0 return (2.0 * tp) / denominator def weighted_f1_from_counts(tp: int, fp: int, fn: int, tn: int) -> float: """Binary weighted F1: F1 of class 1 and F1 of class 0, weighted by each class's true count.""" f1_positive = f1_from_counts(tp, fp, fn) # For class 0 ("no purchase"), true negatives act as TP and false negatives/positives swap roles. f1_negative = f1_from_counts(tn, fn, fp) support_positive = tp + fn support_negative = tn + fp total_support = support_positive + support_negative if total_support == 0: return 0.0 return (support_positive * f1_positive + support_negative * f1_negative) / total_support def weighted_f1(y_true: Sequence[int], y_pred: Sequence[int]) -> float: """Support-weighted mean of the per-class F1 scores for 0/1 labels (0.0 for empty input).""" tp = fp = fn = tn = 0 for truth, pred in zip(y_true, y_pred): if truth == 1 and pred == 1: tp += 1 elif truth == 0 and pred == 1: fp += 1 elif truth == 1 and pred == 0: fn += 1 else: tn += 1 return weighted_f1_from_counts(tp, fp, fn, tn) def best_threshold(y_true: Sequence[int], probs: Sequence[float]) -> Tuple[float, float]: """Return (threshold, score): the predicted probability t that maximizes the weighted F1 of "predict 1 when prob >= t". Ties go to the larger threshold. Raise ValueError on empty input.""" if len(probs) == 0 or len(y_true) != len(probs): raise ValueError("y_true and probs must be non-empty sequences of equal length") # Sort (prob, label) from highest to lowest probability so each group crosses 'prob >= t' once. sorted_pairs = sorted(zip(probs, y_true), key=lambda pair: pair[0], reverse=True) total_positive = sum(y_true) total_negative = len(sorted_pairs) - total_positive tp = 0 fp = 0 best_t = float(sorted_pairs[0][0]) best_score = -1.0 idx = 0 num_rows = len(sorted_pairs) while idx < num_rows: candidate_t = sorted_pairs[idx][0] # Admit all rows tied at candidate_t together, because 'prob >= candidate_t' includes them all. while idx < num_rows and sorted_pairs[idx][0] == candidate_t: if sorted_pairs[idx][1] == 1: tp += 1 else: fp += 1 idx += 1 fn = total_positive - tp tn = total_negative - fp score = weighted_f1_from_counts(tp, fp, fn, tn) # Scanning high-to-low + 1e-12 float tolerance ensures exact ties keep the larger threshold. if score > best_score + 1e-12: best_t = float(candidate_t) best_score = score return best_t, best_score def stratified_split(y: Sequence[int], val_fraction: float = 0.2, seed: int = 0) -> Tuple[List[int], List[int]]: """Return sorted (train, val) index lists; each class sends round(count * val_fraction) rows to val.""" rng = random.Random(seed) train_indices: List[int] = [] val_indices: List[int] = [] # Split class 0 and class 1 independently so both partitions preserve the exact purchase ratio. for label in (0, 1): class_indices = [idx for idx, target_val in enumerate(y) if target_val == label] rng.shuffle(class_indices) val_count = round(len(class_indices) * val_fraction) val_indices.extend(class_indices[:val_count]) train_indices.extend(class_indices[val_count:]) return sorted(train_indices), sorted(val_indices) def fit_model(rows: List[Dict[str, Optional[float]]], y: np.ndarray, numeric: List[str], categorical: List[str]) -> Tuple[Preprocessor, np.ndarray, float]: """Fit a fresh Preprocessor and regularized logistic regression model on the given rows.""" preprocessor = Preprocessor(numeric, categorical).fit(rows) X_matrix = preprocessor.transform(rows) weights, bias = train_logistic_regression(X_matrix, y) return preprocessor, weights, bias def build_submission(train_rows: List[Dict[str, Any]], test_rows: List[Dict[str, Any]], schema: Dict[str, str], id_column: str = "id", target: str = "outcome", val_fraction: float = 0.2, seed: int = 0) -> Dict[str, Any]: """Clean, drop bad columns, tune the threshold on a stratified validation split, refit on all labelled rows and predict the test rows. Return {"unlabelled_rows", "dropped", "threshold", "val_weighted_f1", "submission"}, where submission is a list of (id, 0 or 1) in test-row order. """ # Phase 1: Keep only training rows whose target parses cleanly as 0 or 1. labelled_rows: List[Dict[str, Any]] = [] labels: List[int] = [] for row in train_rows: parsed_label = clean_value(row.get(target), "flag") if parsed_label is not None: labelled_rows.append(row) labels.append(int(parsed_label)) y_all = np.array(labels, dtype=float) # Phase 2: Clean features and choose dropped columns strictly from training data (no test leakage). train_clean = clean_rows(labelled_rows, schema) test_clean = clean_rows(test_rows, schema) dropped = columns_to_drop(train_clean, list(schema)) numeric_cols: List[str] = [] categorical_cols: List[str] = [] for column, kind in schema.items(): if column in dropped: continue if kind in NUMERIC_KINDS: numeric_cols.append(column) else: categorical_cols.append(column) # Phase 3: Fit Preprocessor + model on fit_rows ONLY, then tune threshold on held-out val_rows. fit_idx, val_idx = stratified_split(labels, val_fraction, seed) fit_rows = [train_clean[i] for i in fit_idx] val_rows = [train_clean[i] for i in val_idx] val_labels = [labels[i] for i in val_idx] val_prep, val_w, val_b = fit_model(fit_rows, y_all[fit_idx], numeric_cols, categorical_cols) val_probs = predict_proba(val_prep.transform(val_rows), val_w, val_b) threshold, val_score = best_threshold(val_labels, val_probs) # Phase 4: Refit on 100% of labelled training rows and generate binary test predictions. full_prep, full_w, full_b = fit_model(train_clean, y_all, numeric_cols, categorical_cols) test_probs = predict_proba(full_prep.transform(test_clean), full_w, full_b) submission: List[Tuple[Any, int]] = [] for raw_test_row, prob in zip(test_rows, test_probs): predicted_label = int(prob >= threshold) submission.append((raw_test_row[id_column], predicted_label)) return { "unlabelled_rows": len(train_rows) - len(labelled_rows), "dropped": dropped, "threshold": threshold, "val_weighted_f1": val_score, "submission": submission, } def read_rows(path: str) -> List[Dict[str, str]]: with open(path, newline="") as csv_file: return list(csv.DictReader(csv_file)) def write_submission(path: str, submission: List[Tuple[Any, int]]) -> None: with open(path, "w", newline="") as csv_file: writer = csv.writer(csv_file) writer.writerow(["id", "outcome"]) for row_id, outcome in submission: writer.writerow([row_id, outcome]) if __name__ == "__main__": pipeline_out = build_submission(read_rows("train.csv"), read_rows("test.csv"), EXAMPLE_SCHEMA) print( "dropped:", pipeline_out["dropped"], "threshold:", round(pipeline_out["threshold"], 3), "validation weighted F1:", round(pipeline_out["val_weighted_f1"], 4), ) write_submission("submissions.csv", pipeline_out["submission"])✅ Submit now — all tests should pass.
Intuition & how it works
Think of building a tabular machine-learning submission pipeline like running a strict test kitchen separated from the judges' dining room by a one-way window. First, every raw ingredient is inspected against physical rules (impossible numbers like -1 page views or 1.7 exit rates become cleanly marked None gaps rather than crashing or poisoning averages). Second, empty or unchanging spice jars (> 50% missing or constant columns) are discarded, and portion sizes (medians, means, standard deviations, and category lists) are measured exclusively inside the training kitchen (fit) before transforming validation and test orders (transform). Finally, instead of guessing a 0.50 probability cutoff, we slide the cutoff across sorted validation predictions to maximize weighted F1 — a score that blends the F1 score (the harmonic mean 2 * P * R / (P + R) of precision and recall) of buyers and non-buyers weighted by their class sizes.
Feeding raw CSV columns straight into a classifier with a 0.50 cutoff fails on four fronts at once. Corrupted strings like "error" or out-of-range rates (1.5) hide >50%-missing columns unless cleaned before counting missingness; integer category codes like traffic_type = 4 trick linear weights into assuming code 4 is twice code 2; fitting scalers on train + test together causes data leakage (sneaking evaluation statistics into training); and recounting all n validation predictions for every candidate threshold wastes O(n^2) time while a fixed 0.50 cutoff severely under-scores on imbalanced sessions.
Walk through Example 2's 6-row validation trace (y_true = [1, 0, 1, 0, 0, 0], sorted probabilities [0.92, 0.65, 0.35, 0.28, 0.15, 0.05], 2 buyers and 4 non-buyers):
1. Default 0.50 cutoff: Predicts [1, 1, 0, 0, 0, 0] (TP=1, FP=1, FN=1, TN=3), giving buyer F1 = 0.500, non-buyer F1 = 0.750, and weighted F1 = (2 * 0.500 + 4 * 0.750) / 6 = 2/3 ≈ 0.667.
2. Sorted O(n log n) sweep: Stepping down one probability group to t = 0.35 flips the third session (prob = 0.35, y = 1) from 0 to 1 in O(1) time (TP=2, FP=1, FN=0, TN=3).
3. Peak weighted F1: Buyer F1 jumps to 4/5 = 0.800 and non-buyer F1 rises to 6/7 ≈ 0.857, lifting weighted F1 to 88/105 ≈ 0.838 — a +0.171 gain without altering a single model weight!
Complexity
Let n be the number of training rows, c be the number of schema columns, d be the number of encoded features (2 per numeric column plus num_levels + 1 per categorical column), and E be the number of gradient-descent epochs (500).
- Time —
O(E * n * d + n * log n):- Cleaning & column dropping (
O(n * c)): We visit each cell inrowsonce to parse and domain-check its value, then scan each retained column once to count missing and distinct values. - Preprocessor
fitandtransform(O(n * c + n * d)): Computing numeric medians/means/stds takesO(n)per numeric column, sorting unique category codes takesO(k * log k)fork <= nunique levels, andtransformallocates ann x dzero matrix (O(n * d)) and fillsO(c)active entries per row usingO(1)dictionary lookups (self.level_to_offset). - Logistic regression training (
O(E * n * d)): Each of theEepochs performs two dense matrix-vector multiplications (X @ weightsandX.T @ error) across alln * dentries, which dominates total runtime. - Threshold sweep (
O(n * log n)): Sorting thenvalidation(prob, label)pairs takesO(n * log n), followed by a singleO(n)two-pointer pass that updates(tp, fp, fn, tn)inO(1)per row.
- Cleaning & column dropping (
- Space —
O(n * d + n * c): Storing the cleaned dictionaries usesO(n * c)memory, and the dense encoded feature matrixXusesO(n * d)floats.
Edge cases
- Exact 50% missing boundary: Because the prompt specifies more than 50% missing,
missing_count > 0.5 * total_rowskeeps a column with 5 missing values out of 10 rows and drops 6 out of 10. - Domain bugs masquerading as present text: Cells like
"-1"inpage_countor"1.5"inexit_ratebecomeNonebeforecolumns_to_dropruns, so a column filled mostly with out-of-range bugs is properly dropped. - Constant or single-value columns: Columns with
0or1distinct non-missing values (distinct_count <= 1, e.g.,holiday = 0everywhere plus blanks) carry no signal beyond missingness and are dropped; insidePreprocessor.fit,std == 0falls back to1.0so z-score scaling never divides by zero. - Unseen test categories, missing keys, and
-0.0: A category code appearing only intest.csvproduces all-zero one-hot indicators instead of raising aKeyError; missing dict keys safely default toNoneviarow.get(column); and"-0"normalizes to+0.0so category names format cleanly as"col=0"rather than"col=-0". - Corrupted target labels: Training rows with
outcome = "?"or""are excluded before splitting and tallied inunlabelled_rows. - Tied probabilities and floating-point score ties: Equal probabilities must cross
prob >= tsimultaneously in one batch, and scanning high-to-low withscore > best_score + 1e-12preserves the larger threshold even when algebraically equal F1 scores differ by1e-16float rounding.
Common mistakes
- Fitting preprocessing or
columns_to_dropon combined train + test data: Computing medians, z-score scalers, category levels, or missingness drop lists usingtest.csvleaks test distributions into training. - Checking missingness before domain cleaning: Counting raw non-empty strings lets a column full of
"error"or"999"rates sneak past the 50% filter. - Feeding nominal integer codes straight into a linear model: Treating
user_device(1, 2, 3) as a continuous number forcesweight * 3to be tripleweight * 1instead of one-hot encoding each category. - Using a hardcoded
0.50threshold or tuning on training predictions: Default0.50ignores class weights in weighted F1, while tuning on training predictions overfits the cutoff. - Confusing binary F1, macro F1, and weighted F1: At
15%buyers, predicting all0s gives0.00positive-class F1,~0.46macro F1, and~0.78weighted F1 — always benchmark against the all-zero floor! - Breaking submission formatting: Writing raw float probabilities instead of
0/1integers, shuffling test row order, or dropping rows with missing feature values fromtest.csv.
Follow-up questions
- What strategies work best when positive conversion events make up only a small fraction of all sessions? First compute the majority-class (all-zero) weighted-F1 baseline (
~0.78at15%positives) so you know the true floor, preserve class ratios with stratified splits, and tune the probability cutoff directly for weighted F1 on validation — often the single highest-leverage fix. If logistic regression still under-focuses on buyers during training, apply balanced class weights (n / (2 * n_class)inside log loss, weighting a15%buyer class ~3.33xand85%non-buyers ~0.59x) on the training split only, then re-tune the validation threshold since reweighting shifts raw probabilities upward. - How do you prevent validation or test-set information from leaking into feature engineering and model selection? Enforce a strict
fit/transformboundary: medians, means, standard deviations, category vocabularies, and any supervised target encoding (replacing a category with its smoothed conversion rate, which must be computed out-of-fold) are learned strictly on training rows and applied read-only to validation and test rows. Decidecolumns_to_dropfrom labelled training data alone, audit features for post-outcome leakage (such asorder_confirmation_views), and switch from row-stratified splits to user-grouped or time-based splits if repeat shoppers or sequential weeks span the dataset. - Which initial benchmark models would you build first, and how would you decide whether a more complex model is justified? Always build two baselines immediately: a zero-feature majority-class predictor (predict all
0s) to establish the metric floor, followed by L2-regularized logistic regression with median + missing-flag imputation, one-hot categories, and validation threshold tuning. Once that clean linear pipeline is verified end to end, benchmark gradient-boosted decision trees (such as LightGBM orHistGradientBoostingClassifier), which naturally learn non-linear thresholds and feature interactions (likehigh engagement_score AND promotion == 1) without feature scaling, keeping the tree model only if it beats logistic regression on identical cross-validation folds. - If your pipeline produces a disappointing weighted F1 score on validation, how would you systematically diagnose the bottleneck? Compare against the all-zero weighted-F1 floor first, then inspect the confusion matrix and separate Class-0 vs. Class-1 precision/recall at the chosen threshold to see whether false positives or false negatives hurt more. Next, check target and feature parsing (
clean_valuerates ofNoneper column to ensure valid formats like"True"or percentage strings"25%"weren't wiped out), compare train vs. validation weighted F1 (both low = underfitting / weak features; train high and val low = overfitting or threshold variance), check train-vs-test feature drift, and verifysubmissions.csvhas aligned IDs and0/1integers rather than probabilities.
Alternative approaches
- Histogram-based gradient-boosted trees (
HistGradientBoostingClassifier/ LightGBM): Typically outperforms linear models on session tables because tree splits capture diminishing returns onpage_countandtime_spentplus interactions withpromotion, while handlingNaNvalues natively; keep the exact sameO(n log n)validation threshold sweep on top. - Stratified k-fold out-of-fold threshold tuning: On smaller datasets where a single 20% validation split has only a few dozen buyers, generate out-of-fold validation probabilities across 5 stratified folds and run
best_thresholdonce on allnpooled out-of-fold predictions for a much lower-variance cutoff, averaging the 5 fold models' probabilities ontest.csv. - Probability calibration + ensemble blending: Blending predicted probabilities (
0.5 * p_logreg + 0.5 * p_gbdt) after Platt scaling (fitting a 2-parameter logistic calibration curve on out-of-fold predictions) often smooths variance and lifts weighted F1 at the boundary.
Follow-up questions
- What strategies work best when positive conversion events make up only a small fraction of all sessions?
- How do you prevent validation or test-set information from leaking into feature engineering and model selection?
- Which initial benchmark models would you build first, and how would you decide whether a more complex model is justified?
- If your pipeline produces a disappointing weighted F1 score on validation, how would you systematically diagnose the bottleneck?
Similar questions
- Subsequences With Uniform Letter Counts
- Fix State Immutability, Storage Sync, Accessibility, and URL Routing
- Scalable URL Shortening Service
- Final Position in Circular Passing
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision