KatInterview

Predicting a City's Temperature from Neighboring Towns

Machine LearningModel answer
MediumModel answerMachine Learninglinear-regressionolsfeature-selection

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

  1. Q1. Which location (a town or NYC) has the most variable daily temperature, measured by standard deviation?
  2. Q2. Considering only days when Town2 is between 90 and 100 inclusive, what is the median NYC temperature (rounded to an integer)?
  3. Q3. For each town, fit a one-predictor linear model of NYC on that town. What is the sum of the absolute values of the P slopes (intercepts excluded), rounded to an integer?
  4. Q4. Which single town gives the lowest-MSE model for NYC?
  5. Q5. Which pair of towns gives the lowest-MSE two-predictor model for NYC?

Part 2

  1. Q6. Return a set of five towns that together predict NYC as 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.