Regional Weather Data: Metrics, Forward Selection, Online Slope
Machine LearningModel answerLast updated
Analyze multi-town daily temperature data: define volatility and similarity metrics, fit and validate a regression, run greedy town selection, and derive batch and streaming no-intercept slopes.
You have a table of daily temperature readings. Each row holds a date, the temperature in a large city (call it the target city), and the temperature in each of several surrounding towns on that same date.
Work through the following parts. For each, state your metric or method precisely and explain why you chose it.
-
Which town swings the most? Pick a way to measure how much a town's temperature fluctuates and use it to name the most variable town.
-
Which town looks most like the target city? Pick a similarity measure between a town's series and the target city's series, and use it to name the closest town.
-
Predict the target city's temperature. Build a regression model that uses the towns' temperatures as inputs, and report its mean squared error (MSE). Describe how you split the data.
-
Greedy forward selection. Given an integer
k, start with no towns. At each step add the single town whose inclusion (together with those already chosen) lowers validation MSE the most. Return thekchosen towns and the final MSE. -
Regression through the origin. For one predictor
xand a targety, fity ≈ β·xwith no intercept.- Give the batch solution for a full dataset.
- Then handle a stream of
(x, y)pairs arriving one at a time, updatingβafter each pair without revisiting earlier data.
Discuss pitfalls you would watch for, such as seasonality, leakage, and degenerate inputs.
Hints
Hint 1
Every town shares the same yearly warm-cold cycle. Think about what a metric on raw temperatures really measures, and what you could compute instead (day-to-day changes or deviations from a seasonal average).
Hint 2
Temperatures on neighboring days are almost duplicates. Ask how a random train/validation split would distort MSE, and what split respects time order.
Hint 3
For the no-intercept slope, set the derivative of the squared error to zero. The answer depends on only two running sums, which is exactly what makes a one-pair-at-a-time update cheap.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The central trap in this problem is seasonality: all nearby towns warm and cool together over the year. Metrics computed on raw temperatures mostly capture that shared cycle. The second trap is leakage from random splits on autocorrelated data. A strong answer addresses both explicitly.
Assume a DataFrame sorted by date, with a nyc column and one column per town.
1. Volatility
- Simple option: standard deviation of raw temperature. This mostly reflects the size of the seasonal swing (inland towns usually swing more). It is acceptable only if stated.
- Better option: standard deviation of day-over-day changes,
std(T_t - T_{t-1}). Slow seasonal drift contributes almost nothing, so it measures short-term unpredictability. - Alternative: standard deviation of anomalies (temperature minus the town's average for that calendar day or month).
Handle gaps: difference only truly consecutive dates, or interpolate first. Report the value for every town so the margin between first and second place is visible.
2. Similarity
Name which notion you mean:
- Same level: RMSE or mean absolute difference to the target city. It penalizes a constant offset.
- Same pattern: Pearson correlation. It ignores offset and scale.
Correlation on raw temperatures is roughly 0.95+ for every town because of the shared season, so it barely discriminates. Correlate daily changes or anomalies instead. Compute both a level metric and a pattern metric and comment on disagreements, for example an inland town that tracks the city closely but runs consistently colder.
3. Prediction and evaluation
- Time-ordered split: train on the earliest period, validate on the middle, test on the latest (for instance 60/20/20). Random splits put near-identical neighboring days on both sides and make MSE look unrealistically good.
- Model: OLS with an intercept on same-day town temperatures. The towns are highly collinear, so coefficients are unstable; ridge regression tuned on the validation set is a sensible upgrade.
- Baselines: the training mean, and the best single town. MSE is meaningless without a reference. Expect test RMSE of a few degrees.
- Framing: same-day features mean this is "nowcasting". For true forecasting, use only lagged features.
4. Greedy forward selection
selected = []
for step in range(min(k, m)):
for each town t not in selected:
fit OLS on train using selected + [t]
score = validation MSE
add the town with the lowest score
return selected, its validation MSE
Complexity: O(k·m) model fits for m towns; each fit costs about O(n·p²) with p ≤ k. This is trivial for small k and m.
Caveats:
- Greedy is not optimal. Two towns that are weak alone can be strong together, which greedy forward selection can miss.
- Validation MSE drives the choice, so the final validation MSE is optimistic. Report test MSE as the honest figure.
- The spec asks for exactly
k, so keep adding even if improvement stalls (cap at m ifk > m). Mention that early stopping is a reasonable alternative.
5. Regression through the origin
Minimize L(β) = Σ (yᵢ - β xᵢ)². Setting the derivative to zero:
-2 Σ xᵢ (yᵢ - β xᵢ) = 0 => β = Σ xᵢyᵢ / Σ xᵢ²
Streaming: β depends only on two sufficient statistics, Sxy = Σ xy and Sxx = Σ x². For each new pair:
Sxy += x*y
Sxx += x*x
beta = Sxy / Sxx # if Sxx > 0
This is O(1) time and memory per update. An equivalent recursive form is:
Sxx += x*x
beta += x * (y - beta*x) / Sxx
That reads as "old slope plus prediction error scaled by x / Sxx".
Edge cases:
Sxx == 0(no data, or all x so far are 0): the slope is undefined. ReturnNoneor 0 and document the choice.- Non-stationary data: use a forgetting factor
λ < 1, soS ← λS + new term. - Use floats to avoid integer overflow on long streams. For very long streams, consider compensated summation.
class OnlineSlope:
def __init__(self):
self.sxy = 0.0
self.sxx = 0.0
def update(self, x, y):
self.sxy += x * y
self.sxx += x * x
return self.value()
def value(self):
return None if self.sxx == 0 else self.sxy / self.sxx
def batch_slope(xs, ys):
sxy = sum(x * y for x, y in zip(xs, ys))
sxx = sum(x * x for x in xs)
return None if sxx == 0 else sxy / sxx
Common mistakes
- Using raw-temperature correlation or standard deviation without acknowledging seasonality.
- Random train/test splits on time series.
- Reporting the validation MSE of the greedy-selected model as the final performance.
- Forgetting the undefined-slope case when
Sxx = 0. - Recomputing sums over all history on every streaming update.