Implement Blocked Spatial K-Fold Cross-Validation with a Buffer

Quick Overview

Implement blocked spatial k-fold cross-validation in NumPy: map coordinates to grid-block ids, assign whole blocks to folds, drop training points inside a buffer around validation points, and score a Ridge model per fold. It tests spatial leakage, exact index bookkeeping and fitting preprocessing on the training fold only.

Implement Blocked Spatial K-Fold Cross-Validation with a Buffer

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Random k-fold cross-validation overstates accuracy on spatial data, because nearby points are correlated and a validation point usually has a close neighbor in the training set. Implement blocked spatial k-fold cross-validation in NumPy as three functions: ```python def assign_blocks(coords, block_size, origin=None) -> np.ndarray: ... def spatial_block_kfold(coords, block_size, n_splits, buffer=0.0, seed=None, origin=None) -> list[tuple[np.ndarray, np.ndarray]]: ... def spatial_cv_mse(coords, X, y, block_size, n_splits, alpha=1.0, buffer=0.0, seed=None, origin=None) -> np.ndarray: ... ``` `assign_blocks` maps `(n, 2)` coordinates to integer grid-block ids. `spatial_block_kfold` assigns whole blocks to folds and returns a list of `(train_idx, val_idx)` pairs. `spatial_cv_mse` returns a NumPy array of per-fold validation MSEs. The functions must follow these rules: - `origin` defaults to the per-axis minimum of `coords`. For each point, `col = floor((x - x0) / block_size)` and `row = floor((y - y0) / block_size)`. The block id is `row * n_cols + col`, where `n_cols = max(col) + 1` over all points. - Take the sorted unique occupied block ids. Permute them with `np.random.default_rng(seed).permutation` only when `seed` is set, then split them into `n_splits` contiguous chunks. With `m` occupied blocks, each chunk gets `m // n_splits` blocks and the first `m % n_splits` chunks get one extra. Fold `i` validates on the points whose block is in chunk `i`. - Return the train and validation indices sorted. If `buffer > 0`, keep only the training points whose Euclidean distance to the nearest validation point is strictly greater than `buffer`. - `spatial_cv_mse` fits `StandardScaler` and `Ridge(alpha)` on the training fold only and scores the validation fold by mean squared error. - Raise `ValueError` when `coords` is not shaped `(n, 2)`, `block_size <= 0`, any point lies below the origin, `n_splits` is outside `[2, number of occupied blocks]`, or `buffer < 0`. Example: ```python assign_blocks([[1, 1], [3, 1], [5.5, 3.2], [1, 5], [4.9, 4.9]], 2.0, origin=(0, 0)) # -> [0, 1, 5, 6, 8] coords = [[0.1, 0], [0.9, 0], [1.1, 0], [1.9, 0], [2.1, 0], [2.9, 0]] spatial_block_kfold(coords, 1.0, 3, buffer=0.25, origin=(0, 0)) # -> [([3, 4, 5], [0, 1]), ([0, 5], [2, 3]), ([0, 1, 2], [4, 5])] ``` ```hint Validation mask Give every point its block id first. A vectorized membership test of those ids against the current chunk of blocks gives the validation mask, and its complement gives the training candidates. ``` ```hint Buffer and scaling For the buffer you only need each training candidate's distance to its nearest validation point. In the scoring function, check which rows the scaler sees when it learns its mean and variance. ``` ### Constraints & Assumptions - `coords` is array-like with shape `(n, 2)`. `X` has shape `(n, d)` and `y` has shape `(n,)`, aligned row by row with `coords`. - Indices come back as integer NumPy arrays; the example prints them as lists. - `seed=None` keeps the blocks in ascending id order. Any integer seed, including 0, triggers the permutation. - Use NumPy and scikit-learn (`StandardScaler`, `Ridge`). ### What a Strong Answer Covers - Block ids that follow the floor formula exactly, including the default origin and the below-origin check. - Fold construction that keeps every block inside one fold, with the exact chunk sizes and the seed-only permutation. - The strict buffer rule applied to training points only, with sorted index output. - Scaler and Ridge fitted on the training fold alone, plus every listed `ValueError` case. - The time and memory cost of the buffer step and where it stops scaling. ### Follow-up Questions - How would you choose `block_size` and `buffer` in practice? - The folds have equal block counts, but blocks can hold very different numbers of points. How would you balance the sample counts across folds? - The buffer step builds an `O(n_train × n_val)` distance matrix. How would you scale it to large datasets?

Overview: Implement blocked spatial k-fold cross-validation in NumPy: map coordinates to grid-block ids, assign whole blocks to folds, drop training points inside a buffer around validation points, and score a Ridge model per fold. It tests spatial leakage, exact index bookkeeping and fitting preprocessing on the training fold only.

PracHub logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Random k-fold cross-validation overstates accuracy on spatial data, because nearby points are correlated and a validation point usually has a close neighbor in the training set. Implement blocked spatial k-fold cross-validation in NumPy as three functions:

def assign_blocks(coords, block_size, origin=None) -> np.ndarray: ...

def spatial_block_kfold(coords, block_size, n_splits, buffer=0.0, seed=None, origin=None) -> list[tuple[np.ndarray, np.ndarray]]: ...

def spatial_cv_mse(coords, X, y, block_size, n_splits, alpha=1.0, buffer=0.0, seed=None, origin=None) -> np.ndarray: ...

assign_blocks maps (n, 2) coordinates to integer grid-block ids. spatial_block_kfold assigns whole blocks to folds and returns a list of (train_idx, val_idx) pairs. spatial_cv_mse returns a NumPy array of per-fold validation MSEs.

The functions must follow these rules:

  • origin defaults to the per-axis minimum of coords . For each point, col = floor((x - x0) / block_size) and row = floor((y - y0) / block_size) . The block id is row * n_cols + col , where n_cols = max(col) + 1 over all points.
  • Take the sorted unique occupied block ids. Permute them with np.random.default_rng(seed).permutation only when seed is set, then split them into n_splits contiguous chunks. With m occupied blocks, each chunk gets m // n_splits blocks and the first m % n_splits chunks get one extra. Fold i validates on the points whose block is in chunk i .
  • Return the train and validation indices sorted. If buffer > 0 , keep only the training points whose Euclidean distance to the nearest validation point is strictly greater than buffer .
  • spatial_cv_mse fits StandardScaler and Ridge(alpha) on the training fold only and scores the validation fold by mean squared error.
  • Raise ValueError when coords is not shaped (n, 2) , block_size <= 0 , any point lies below the origin, n_splits is outside [2, number of occupied blocks] , or buffer < 0 .

Example:

assign_blocks([[1, 1], [3, 1], [5.5, 3.2], [1, 5], [4.9, 4.9]], 2.0, origin=(0, 0))
# -> [0, 1, 5, 6, 8]

coords = [[0.1, 0], [0.9, 0], [1.1, 0], [1.9, 0], [2.1, 0], [2.9, 0]]
spatial_block_kfold(coords, 1.0, 3, buffer=0.25, origin=(0, 0))
# -> [([3, 4, 5], [0, 1]), ([0, 5], [2, 3]), ([0, 1, 2], [4, 5])]

Constraints & Assumptions

  • coords is array-like with shape (n, 2) . X has shape (n, d) and y has shape (n,) , aligned row by row with coords .
  • Indices come back as integer NumPy arrays; the example prints them as lists.
  • seed=None keeps the blocks in ascending id order. Any integer seed, including 0, triggers the permutation.
  • Use NumPy and scikit-learn ( StandardScaler , Ridge ).

What a Strong Answer Covers Guidance

  • Block ids that follow the floor formula exactly, including the default origin and the below-origin check.
  • Fold construction that keeps every block inside one fold, with the exact chunk sizes and the seed-only permutation.
  • The strict buffer rule applied to training points only, with sorted index output.
  • Scaler and Ridge fitted on the training fold alone, plus every listed ValueError case.
  • The time and memory cost of the buffer step and where it stops scaling.

Follow-up Questions Guidance

  • How would you choose block_size and buffer in practice?
  • The folds have equal block counts, but blocks can hold very different numbers of points. How would you balance the sample counts across folds?
  • The buffer step builds an O(n_train × n_val) distance matrix. How would you scale it to large datasets?