KatInterview

Temperature Data: Stats, Regression, and Greedy Feature Selection

Machine LearningModel answer
MediumModel answerMachine Learningpandasnumpylinear-regression

Last updated

Given daily temperature readings for NYC and several towns, compute variability stats, fit linear regressions, and select five predictors via greedy forward search.

You have a pandas DataFrame with N daily temperature readings. One column is named NYC (the target variable). All other columns represent candidate predictor towns, and there are at least five of them. One column is named Town2. All values are finite numbers with no missing entries.

Implement two functions:

def q1_q5(df) -> list:
    ...

def q6(df) -> list[str]:
    ...

q1_q5(df) — return a list with exactly five elements

[
  highest_variance_column,       # position 0
  filtered_median_rounded,       # position 1
  abs_slope_sum_rounded,         # position 2
  best_single_predictor,         # position 3
  [best_pair_town_a, best_pair_town_b]  # position 4
]

Position 0 — Column with the most spread

Find the column with the largest population standard deviation (ddof=0). This search includes NYC itself. Break any tie by choosing the lexicographically smallest column name.

Position 1 — Conditional median

Filter to rows where Town2 is between 90 and 100, inclusive. Take the median of NYC values in that subset and round it to the nearest integer (half values round away from zero). If no rows satisfy the filter, raise a ValueError.

Position 2 — Sum of absolute slopes

Fit a separate simple linear regression (with intercept) of NYC on each individual candidate town. Sum the absolute values of all the resulting slope coefficients, then round the total once to the nearest integer (half values round away from zero). A perfectly constant predictor column has a slope of zero.

Position 3 — Best single predictor

From those same single-town regressions, pick the town whose model produces the lowest in-sample mean squared error. Break exact MSE ties by choosing the lexicographically smallest town name.

Position 4 — Best two-town model

Enumerate every unordered pair of candidate towns. Fit a two-predictor linear regression (with intercept) for each pair. Return the pair with the lowest in-sample MSE as a two-element list sorted in lexicographic order. Break exact MSE ties by comparing the sorted town-name tuples lexicographically. Use the minimum-norm least-squares solution if a pair is rank-deficient.


q6(df) — return a list of exactly five town names

Use greedy forward selection:

  1. Start with no selected towns.
  2. At each of five steps, try adding each remaining candidate town to the current set. Fit a linear regression (with intercept) on the combined set for every candidate. Select the town that produces the lowest MSE when added. Break ties by choosing the lexicographically smallest town name.
  3. Return the five chosen names in the order they were selected.

This greedy approach is an approximation and is not guaranteed to find the globally optimal five-town subset.


Constraints

  • At least one row; all values numeric and non-missing.
  • All regressions include an intercept and are scored by in-sample MSE on all rows.
  • Population standard deviation (ddof=0) throughout.
  • For rank-deficient designs, use the minimum-norm least-squares solution (e.g., np.linalg.lstsq with rcond=None).
  • "Round to nearest integer" means half values round away from zero — use decimal.Decimal or equivalent rather than Python's built-in round(), which does banker's rounding.

Hints

Hint 1

For the half-away-from-zero rounding, Python's built-in round() uses banker's rounding and will give wrong answers on exact halves. Use `decimal.Decimal` with `ROUND_HALF_UP`, or replicate it with `int(x + 0.5)` for positive values and `int(x - 0.5)` for negative ones.

Hint 2

np.linalg.lstsq handles both the constant-predictor (rank-1) and duplicate-column (rank-deficient pair) cases automatically when you pass rcond=None. You don't need special-case logic — just build the design matrix with np.column_stack and an intercept column of ones.

Hint 3

For greedy forward selection, you're refitting from scratch at every candidate evaluation step, not updating an existing model. Each of the five rounds fits (number of remaining candidates) separate regressions, each using all currently selected towns plus the one being evaluated.