Temperature Data: Stats, Regression, and Greedy Feature Selection
Machine LearningModel answerLast 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:
- Start with no selected towns.
- 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.
- 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.lstsqwithrcond=None). - "Round to nearest integer" means half values round away from zero — use
decimal.Decimalor equivalent rather than Python's built-inround(), 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines four distinct sub-tasks under one data model. The key is keeping them cleanly separated and respecting the exact tie-breaking and rounding rules, which is where most implementations go wrong.
Rounding correctly
Python's built-in round() uses banker's rounding (round half to even), so round(0.5) returns 0. The problem requires half-away-from-zero. The safest approach:
from decimal import Decimal, ROUND_HALF_UP
def half_up_round(x):
return int(Decimal(str(x)).quantize(Decimal('1'), rounding=ROUND_HALF_UP))
Part 1: Population std and conditional median
import pandas as pd
import numpy as np
def q1_q5(df: pd.DataFrame) -> list:
# Position 0: largest population std, lex tiebreak
stds = df.std(ddof=0)
max_std = stds.max()
tied = stds[stds == max_std].index.tolist()
highest_variance_column = sorted(tied)[0]
# Position 1: conditional median with required error
subset = df[(df["Town2"] >= 90) & (df["Town2"] <= 100)]
if subset.empty:
raise ValueError("No rows where Town2 is between 90 and 100 inclusive.")
filtered_median_rounded = half_up_round(subset["NYC"].median())
Common mistake: applying ddof=1 (sample std) instead of ddof=0, or excluding NYC from the std comparison.
Part 2: Single-town regressions
y = df["NYC"].values
towns = [c for c in df.columns if c != "NYC"]
n = len(y)
slopes = {}
mse_single = {}
for town in towns:
x = df[town].values
X = np.column_stack([x, np.ones(n)])
coeffs, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
slope = coeffs[0]
slopes[town] = slope
preds = X @ coeffs
mse_single[town] = np.mean((y - preds) ** 2)
# Position 2: sum of absolute slopes, rounded once
abs_slope_sum_rounded = half_up_round(sum(abs(slopes[t]) for t in towns))
# Position 3: best single predictor, lex tiebreak
min_mse = min(mse_single.values())
best_single_predictor = sorted(
t for t in towns if mse_single[t] == min_mse
)[0]
np.linalg.lstsq naturally returns slope zero for a constant column (rank-deficient case), so no special handling needed there.
Part 3: Best two-town model
from itertools import combinations
best_pair = None
best_pair_mse = float("inf")
for t1, t2 in combinations(towns, 2):
X = np.column_stack([df[t1].values, df[t2].values, np.ones(n)])
coeffs, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
preds = X @ coeffs
mse = np.mean((y - preds) ** 2)
pair = tuple(sorted([t1, t2]))
if (mse < best_pair_mse) or (mse == best_pair_mse and pair < best_pair):
best_pair_mse = mse
best_pair = pair
return [
highest_variance_column,
filtered_median_rounded,
abs_slope_sum_rounded,
best_single_predictor,
list(best_pair),
]
The tie-break compares sorted tuples lexicographically, which Python tuple comparison handles naturally. The minimum-norm property of lstsq ensures determinism when two town columns are identical (or linearly dependent).
Complexity: O(P²) pair fits, each O(N) — acceptable for typical feature set sizes.
Part 4: Greedy forward selection
def q6(df: pd.DataFrame) -> list[str]:
y = df["NYC"].values
n = len(y)
towns = [c for c in df.columns if c != "NYC"]
selected = []
remaining = list(towns)
for _ in range(5):
best_town = None
best_mse = float("inf")
for candidate in remaining:
cols = selected + [candidate]
X = np.column_stack([df[c].values for c in cols] + [np.ones(n)])
coeffs, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
preds = X @ coeffs
mse = np.mean((y - preds) ** 2)
if (mse < best_mse) or (mse == best_mse and candidate < best_town):
best_mse = mse
best_town = candidate
selected.append(best_town)
remaining.remove(best_town)
return selected
Complexity: Five rounds × up to P candidates each, so roughly 5P model fits. Each fit is O(NP) with lstsq, giving O(NP²) overall — fine for hundreds of towns and thousands of rows.
Important caveat: Greedy forward selection is not globally optimal. It can miss the best five-town subset if the jointly informative combination isn't discoverable step by step. Exhaustive search over all C(P, 5) subsets would be optimal but is exponentially more expensive.
Common mistakes to avoid
- Using
ddof=1instead ofddof=0for standard deviation. - Forgetting to include
NYCin the std comparison. - Using Python's
round()for half values — gives wrong results on exact halves. - Raising the
ValueErroronly whenTown2is missing entirely rather than when the filtered subset is empty. - In greedy selection, evaluating candidates only once globally rather than re-evaluating the combined set at each step.
- Sorting the pair after the MSE comparison instead of before, which breaks the tie rule.