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):

  1. parse_number(value: Any) -> Optional[float]
    • Strip surrounding whitespace if value is a string and return None when the lowercased string is in MISSING_TOKENS.
    • Convert value to float, returning None if value is None, cannot be parsed, or produces NaN or +/-inf. Normalize -0.0 to +0.0.
  2. clean_value(value: Any, kind: str) -> Optional[float]
    • Parse value with parse_number and validate domain bounds:
      • "count" and "category": whole numbers >= 0 (x >= 0 and x == floor(x)).
      • "duration": any finite number >= 0.
      • "rate": any finite number in [0.0, 1.0].
      • "flag": 0.0 or 1.0.
      • "score": any finite float.
    • Return None when validation fails, and raise ValueError for an unrecognized kind.
  3. 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) in schema.
  4. 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 None count strictly exceeds max_missing * len(rows) or that contain at most 1 distinct non-None value.
  5. Preprocessor(numeric: Sequence[str], categorical: Sequence[str])
    • fit(rows) learns statistics strictly from training rows and populates self.feature_names:
      • Each numeric column col emits [col, f"{col}__missing"]: impute None with the median of present values in col (0.0 if all values are None), compute the population mean and population standard deviation (np.std, using 1.0 when std == 0.0) on the median-filled training column, and set the missing indicator to 1.0 iff the input cell was None.
      • Each categorical column col emits one 0.0/1.0 indicator per sorted distinct non-None training value named f"{col}={level:g}", followed by f"{col}=missing". Any test level unseen during fit maps to all zeros across that column's indicators.
    • transform(rows) returns a float NumPy matrix of shape (len(rows), len(self.feature_names)).
  6. 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 w and zero intercept b (returning immediately if X has 0 rows), run epochs steps of full-batch gradient descent minimizing mean binary cross-entropy loss plus (l2 / 2) * ||w||^2 (do not regularize b), using sigmoid clipped to [-35.0, 35.0].
  7. weighted_f1(y_true: Sequence[int], y_pred: Sequence[int]) -> float
    • Return the support-weighted mean of the binary Class 1 F1 score and Class 0 F1 score (0.0 on empty input, and 0.0 for a class when 2 * TP + FP + FN == 0).
  8. best_threshold(y_true: Sequence[int], probs: Sequence[float]) -> Tuple[float, float]
    • Among candidate cutoffs t taken from probs under the rule predict 1 iff prob >= t, return (best_t, best_weighted_f1). Break ties in score by choosing the largest threshold t. Raise ValueError if probs is empty or len(y_true) != len(probs).
  9. stratified_split(y: Sequence[int], val_fraction: float = 0.2, seed: int = 0) -> Tuple[List[int], List[int]]
    • Using random.Random(seed), iterate label in (0, 1), shuffle the indices where y[i] == label, place the first round(count * val_fraction) indices into validation and the remainder into training, and return (sorted(train_idx), sorted(val_idx)).
  10. build_submission(train_rows, test_rows, schema, id_column="id", target="outcome", val_fraction=0.2, seed=0) -> Dict[str, Any] and write_submission(path, submission) -> None
    • Keep only training rows whose target cleans to 0.0 or 1.0 as "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 refit Preprocessor and logistic regression on all labelled training rows to classify test_rows in order as [(row[id_column], int(prob >= threshold)), ...].
    • write_submission writes a CSV file with header id,outcome followed by each pair.

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 produces feature_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 (0 or 1); test rows carry no target column.
  • Column dropping uses a strict inequality (missing_count > max_missing * len(rows)), so a column missing in exactly 50% of training rows is retained when max_missing = 0.5 (provided it has at least 2 distinct non-missing values).
  • All preprocessing statistics and column-drop decisions must be derived strictly from training rows without inspecting validation or test features.
  • best_threshold must run in O(n log n) time so validation splits with tens of thousands of rows finish well under a second.

Step-by-step walkthrough

  1. Understand the goal, metric, and schema contract

    We receive a labelled training CSV (outcome in {0, 1}) and an unlabelled test CSV carrying session attributes plus id. Our pipeline must produce id,outcome binary 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 to None so 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_device or traffic_type represent unordered labels rather than magnitudes, so we expand them into one-hot 0/1 indicators 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",
    }
    
  2. Clean raw CSV cells and turn impossible values into missing

    csv.DictReader yields 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:

    1. parse_number(value) strips whitespace, rejects missing-value tokens, junk strings, NaN, and +/-inf, and normalizes -0.0 to +0.0 (so formatting category 0.0 with :g never produces "-0").
    2. clean_value(value, kind) checks domain validity (count and category must be whole numbers >= 0; duration >= 0; rate in [0, 1]; flag in {0, 1}; score any finite float) and returns None whenever 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_rows
    
  3. Drop 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_drop after clean_rows: A rate column holding "1.4" in 3 of 4 rows looks populated as raw strings, yet turns into 75% None after domain validation and gets dropped.
    • Strict > comparison: Exceeding 50% 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 (like constant_col = 1 everywhere) 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
    
  4. 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 inside Preprocessor.transform(any_rows):

    • Numeric column col expands into two features [col, col__missing]: fill None with the training median (unlike the mean, a median is not pulled around by extreme outlier sessions), set col__missing = 1.0 when None (since "missingness" itself can predict drop-off!), and z-score standardize (value - train_mean) / train_std so gradient descent converges smoothly (train_std == 0 falls back to 1.0).
    • Categorical column col expands into one 0/1 indicator per sorted level seen in training (col=1, col=2, ...) plus col=missing. If test.csv contains a brand-new category code (like device = 9), every indicator stays 0.0 instead of crashing.

    Here is how Example 1's retained slice (views numeric with cleaned values [2.0, 6.0, None, 10.0], channel categorical 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.0
    
    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
    
  5. Train a regularized logistic regression baseline

    Logistic regression predicts purchase probability by passing a linear score z = X @ w + b through the sigmoid curve 1 / (1 + exp(-z)), squashing any real number smoothly into (0, 1). We find weights w and bias b by 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 intercept b unpenalized 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 bias
    

    Clipping z to [-35, 35] inside sigmoid prevents np.exp(-z) from overflowing float64 when z is very negative, while changing probabilities by less than 1e-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)
    
  6. 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 to 2 * TP / (2 * TP + FP + FN) (defined as 0.0 when 2 * 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) with support_1 = tp + fn. - Class 0 (outcome == 0): treats "no purchase" as the target class, so tn plays the role of true positives, fn acts as false positives (predicted 0 when truth was 1), and fp acts as false negatives (predicted 1 when truth was 0), with support_0 = tn + fp.

    Notice what this means when 85% of sessions are non-buyers: 85% of weighted F1 comes from Class 0! Predicting 0 for every row already scores 0.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)
    
  7. Find the optimal threshold in O(n log n) with a sorted sweep

    Checking every distinct predicted probability t by recomputing all n predictions from scratch takes O(n^2) time. Instead, sort (prob, label) pairs once from highest probability down to lowest:

    • As we lower candidate_t to the next distinct probability, every row equal to candidate_t flips from predicted 0 to predicted 1 (because our rule is prob >= candidate_t, tied rows must cross together in an inner while loop!).
    • Each row updates tp or fp once in O(1) time, while fn = total_positive - tp and tn = total_negative - fp.
    • Because we sweep from largest threshold to smallest, updating best_t only when score > best_score + 1e-12 guarantees ties go to the larger threshold — even when two algebraically identical fractions (like (6 * 1/2 + 3 * 3/5) / 9 and (6 * 4/5) / 9, both 8/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 = .167
    

    The sweep selects threshold = 0.35 (88/105 ≈ 0.838), beating the naive 0.50 cutoff (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
    
  8. Assemble the leak-free validation and submission pipeline

    Now wire everything together cleanly inside build_submission so 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)
    
    1. Filter target bugs: Skip training rows whose outcome is missing or corrupted (like "?"), recording their count in unlabelled_rows.
    2. Clean and drop columns on train_clean only: Never inspect test_rows when deciding dropped.
    3. Stratified validation tuning: stratified_split shuffles Class 0 and Class 1 separately so both fit_rows (80%) and val_rows (20%) keep the exact same purchase rate. Fit Preprocessor and logistic regression strictly on fit_rows, then pick threshold on val_rows.
    4. Final refit & CSV export: Refit Preprocessor and logistic regression on 100% of train_clean to use all labeled data, score test_clean with threshold, and write id,outcome in 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,
        }
    
  9. 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 in rows once to parse and domain-check its value, then scan each retained column once to count missing and distinct values.
    • Preprocessor fit and transform (O(n * c + n * d)): Computing numeric medians/means/stds takes O(n) per numeric column, sorting unique category codes takes O(k * log k) for k <= n unique levels, and transform allocates an n x d zero matrix (O(n * d)) and fills O(c) active entries per row using O(1) dictionary lookups (self.level_to_offset).
    • Logistic regression training (O(E * n * d)): Each of the E epochs performs two dense matrix-vector multiplications (X @ weights and X.T @ error) across all n * d entries, which dominates total runtime.
    • Threshold sweep (O(n * log n)): Sorting the n validation (prob, label) pairs takes O(n * log n), followed by a single O(n) two-pointer pass that updates (tp, fp, fn, tn) in O(1) per row.
  • Space — O(n * d + n * c): Storing the cleaned dictionaries uses O(n * c) memory, and the dense encoded feature matrix X uses O(n * d) floats.

Edge cases

  • Exact 50% missing boundary: Because the prompt specifies more than 50% missing, missing_count > 0.5 * total_rows keeps 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" in page_count or "1.5" in exit_rate become None before columns_to_drop runs, so a column filled mostly with out-of-range bugs is properly dropped.
  • Constant or single-value columns: Columns with 0 or 1 distinct non-missing values (distinct_count <= 1, e.g., holiday = 0 everywhere plus blanks) carry no signal beyond missingness and are dropped; inside Preprocessor.fit, std == 0 falls back to 1.0 so z-score scaling never divides by zero.
  • Unseen test categories, missing keys, and -0.0: A category code appearing only in test.csv produces all-zero one-hot indicators instead of raising a KeyError; missing dict keys safely default to None via row.get(column); and "-0" normalizes to +0.0 so 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 in unlabelled_rows.
  • Tied probabilities and floating-point score ties: Equal probabilities must cross prob >= t simultaneously in one batch, and scanning high-to-low with score > best_score + 1e-12 preserves the larger threshold even when algebraically equal F1 scores differ by 1e-16 float rounding.

Common mistakes

  • Fitting preprocessing or columns_to_drop on combined train + test data: Computing medians, z-score scalers, category levels, or missingness drop lists using test.csv leaks 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 forces weight * 3 to be triple weight * 1 instead of one-hot encoding each category.
  • Using a hardcoded 0.50 threshold or tuning on training predictions: Default 0.50 ignores 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 all 0s gives 0.00 positive-class F1, ~0.46 macro F1, and ~0.78 weighted F1 — always benchmark against the all-zero floor!
  • Breaking submission formatting: Writing raw float probabilities instead of 0/1 integers, shuffling test row order, or dropping rows with missing feature values from test.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.78 at 15% 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 a 15% buyer class ~3.33x and 85% 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 / transform boundary: 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. Decide columns_to_drop from labelled training data alone, audit features for post-outcome leakage (such as order_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 or HistGradientBoostingClassifier), which naturally learn non-linear thresholds and feature interactions (like high 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_value rates of None per 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 verify submissions.csv has aligned IDs and 0/1 integers 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 on page_count and time_spent plus interactions with promotion, while handling NaN values natively; keep the exact same O(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_threshold once on all n pooled out-of-fold predictions for a much lower-variance cutoff, averaging the 5 fold models' probabilities on test.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

Similar questions

More HackerRank interview questions

All 5 HackerRank questions →