Predicting a City's Temperature from Neighboring Towns
Machine LearningModel answerLast updated
Use OLS with an intercept on daily temperature data to summarize variability, fit per-town slopes, and select the best one, two, or five predictor towns by in-sample MSE.
Predicting a City's Temperature from Neighboring Towns
You have a table of daily temperature readings in degrees Fahrenheit. Each row is one calendar day. One column, NYC, holds the city's reading. P other columns, Town1 to TownP, hold the readings of nearby towns for that same day.
Rows are aligned by day and nothing is missing. Assume a few thousand rows and P between roughly 10 and 30.
Ground rules:
- "Linear model" always means ordinary least squares (OLS) with an intercept.
- Model quality is the in-sample mean squared error (MSE) on the full dataset. No train/test split.
- If you round, round only the final value, to the nearest integer.
Part 1
Write a function that answers:
- Q1. Which location (a town or NYC) has the most variable daily temperature, measured by standard deviation?
- Q2. Considering only days when
Town2is between 90 and 100 inclusive, what is the medianNYCtemperature (rounded to an integer)? - Q3. For each town, fit a one-predictor linear model of
NYCon that town. What is the sum of the absolute values of thePslopes (intercepts excluded), rounded to an integer? - Q4. Which single town gives the lowest-MSE model for
NYC? - Q5. Which pair of towns gives the lowest-MSE two-predictor model for
NYC?
Part 2
- Q6. Return a set of five towns that together predict
NYCas well as possible under the same criterion.
What to discuss
- Whether the std convention (n vs n-1) or tie-breaking affects your answers.
- How you handle an even-sized set when taking a median, and which rounding convention you use.
- How large the search spaces for Q5 and Q6 are, and whether exhaustive search is feasible.
- How you would verify your implementation.
Hints
Hint 1
For OLS with an intercept, center every column first. After centering, the intercept disappears and everything depends on sums of squares and cross-products, which you can compute once in a single matrix product.
Hint 2
For one predictor, the minimum squared error is the target's total sum of squares times (1 - r^2), so the best single town is the one with the largest absolute correlation with NYC. Do not assume the best pair is just the two best singles, because predictors can be redundant with each other.
Hint 3
Count the subsets: C(30,5) is about 142,500. Once the centered Gram matrix is built, each subset needs only a tiny 5x5 solve, so exact search is feasible. Keep greedy forward selection as the fallback for larger P, and know how it can fail.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Center every column (subtract its mean). With an intercept, OLS then reduces to sums of squares and cross-products. Build the centered Gram matrix once:
G = Zc^T Zc, where Z has NYC first and the towns after it. This costs O(nP^2).
For a set of predictors S, the minimum sum of squared errors is
SSE(S) = G_yy - G_Sy^T G_SS^{-1} G_Sy
and MSE = SSE / n. Since n is the same for every model, ranking by SSE is the same as ranking by MSE. Scoring any subset of size k now costs one k x k solve, independent of n.
Question by question
Q1. Take the argmax of per-column standard deviation. Sample (n-1) and population (n) versions differ by a constant factor shared by all columns, so the winner is the same.
Q2. Filter rows with 90 <= Town2 <= 100, take the median of NYC, and round at the end. With an even count the median is the mean of the two middle values. State your rounding rule (half-up is the usual reading; Python's built-in round uses banker's rounding). If the filter is empty, raise an error rather than return NaN.
Q3. The slope for town j is G_jy / G_jj (covariance over variance). Sum the absolute values, then round once. The common bug is fitting with a ones column and summing the whole coefficient vector, which pulls in the intercepts. Skip any constant column, whose variance is zero.
Q4. With one predictor, SSE = G_yy (1 - r^2). Since G_yy is fixed, the best town is the one with the largest |r| with NYC. Derivation: SSE(b) = G_yy - 2b G_xy + b^2 G_xx is a quadratic in b, minimized at b = G_xy / G_xx, giving G_yy - G_xy^2 / G_xx. This equivalence to correlation depends on having an intercept.
Q5. Exhaustive search over all pairs: at most C(30,2) = 435 two-by-two solves, which is trivial. Do not simply take the top two from Q4. Towns that each correlate strongly with NYC usually correlate strongly with each other, so the second adds little new information. The best pair may include a town that is only moderately good alone but complementary to the other.
Q6. Size the search first. C(30,5) = 142,506 subsets. With the Gram trick, each costs one 5x5 solve, so the exact search finishes in seconds. Even refitting naively on 3,000 rows (about 10^5 flops each) totals roughly 10^10 flops, which is still feasible. So for P up to about 30, do the exact search and say so. If C(P,5) becomes too large, fall back to greedy forward selection (about 5P fits). Greedy can fail when predictors are correlated: a pair can be jointly excellent even though neither member is the best single addition at its step. Swap-based refinement or L1 methods are other heuristics.
Complexity
| Step | Time |
|---|---|
| Gram matrix | O(nP^2) |
| Q1 to Q4 | O(nP) |
| Q5 after Gram | O(P^2) small solves |
| Q6 exact | O(C(P,5) * 5^3) |
| Q6 greedy | O(5P * 5^3) |
Reference code
import itertools, math
import numpy as np
import pandas as pd
def half_up(x):
return int(math.floor(x + 0.5))
def gram(df):
towns = [c for c in df.columns if c != "NYC"]
Z = df[["NYC"] + towns].to_numpy(float)
Zc = Z - Z.mean(axis=0)
return Zc.T @ Zc, towns
def sse(G, idx):
idx = list(idx)
A = G[np.ix_(idx, idx)]
b = G[idx, 0]
beta = np.linalg.lstsq(A, b, rcond=None)[0]
return float(G[0, 0] - b @ beta)
def part1(df):
G, towns = gram(df)
P = len(towns)
q1 = df.std(ddof=1).idxmax()
sel = df.loc[df["Town2"].between(90, 100), "NYC"]
if sel.empty:
raise ValueError("no days with Town2 in [90, 100]")
q2 = half_up(sel.median())
q3 = half_up(sum(abs(G[j, 0] / G[j, j])
for j in range(1, P + 1) if G[j, j] > 0))
q4 = towns[int(np.argmin([sse(G, [j]) for j in range(1, P + 1)]))]
pair = min(itertools.combinations(range(1, P + 1), 2),
key=lambda s: sse(G, s))
q5 = tuple(towns[j - 1] for j in pair)
return q1, q2, q3, q4, q5
def part2(df, k=5, max_exact=2_000_000):
G, towns = gram(df)
P = len(towns)
cand = range(1, P + 1)
if math.comb(P, k) <= max_exact:
best = min(itertools.combinations(cand, k), key=lambda s: sse(G, s))
else:
best = []
for _ in range(k):
best.append(min((j for j in cand if j not in best),
key=lambda j: sse(G, best + [j])))
return {towns[j - 1] for j in best}
Using lstsq instead of inv keeps collinear subsets safe: the SSE is still well defined even if the coefficients are not unique.
Verification
Check sse against a direct np.linalg.lstsq fit on the raw design matrix with a column of ones, and compare residual sums of squares. They should agree to floating-point tolerance.
Edge cases and common mistakes
- Empty Q2 filter: raise an error.
- Constant town column: slope undefined, skip it.
- Ties: break deterministically (for example by column order) and say so.
- Including intercepts in the Q3 sum.
- Choosing the top two singles as the best pair.
- Fitting without an intercept, which breaks the correlation shortcut.
- Rounding intermediate values.
- Using
invon near-singular matrices. - Reporting in-sample MSE as if it were generalization error. With 5 of 30 predictors chosen by search, in-sample MSE is optimistic; a held-out split or cross-validation would be the next step.