Random Forest Proximity Imputation (RF-Impute) for Missing Values

Quick Overview

Implement random forest proximity imputation for a numeric matrix with missing values: a class-aware median fill, then repeated forest fits whose shared-leaf proximities reweight the observed values. It tests careful masking, convergence logic, input immutability and the memory cost of an n by n proximity matrix.

Random Forest Proximity Imputation (RF-Impute) for Missing Values

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Given a float matrix `X` with `NaN` entries and class labels `y`, implement Breiman's RF-Impute. Fill gaps roughly, then repeatedly refine them with random-forest proximities. Return `(X_imputed, n_iterations)`. No function may mutate its inputs. Implement these functions: - `proximity_from_leaves(leaves)`: `leaves` is `(n_samples, n_trees)`. Return `P[i, j]` = fraction of trees where `i` and `j` share a leaf, with diagonal `1.0`. - `initial_fill(X, y)`: each `NaN` gets the median of observed values in its column for its class. If the class has none, use the column's overall observed median. If the column is fully missing, use `0.0`. - `impute_step(X_filled, missing_mask, proximity)`: each missing `(i, j)` becomes the mean of observed rows' column-`j` values, weighted by `proximity[i, obs]`. If the weights sum to 0, keep the current value. Observed entries never change. - `rf_impute(X, y, n_estimators=50, max_iter=5, tol=1e-4, random_state=0)`: if there is no `NaN`, return `(X.copy(), 0)`. Otherwise each iteration fits `RandomForestClassifier(n_estimators=n_estimators, random_state=random_state)` on the current matrix, builds proximities from `rf.apply` on that matrix, then applies one `impute_step`. - Stop when the max absolute change over missing entries is strictly `< tol`, or after `max_iter` iterations. Return the number of iterations performed. ```hint Which cells are missing After the rough fill the matrix has no `NaN` left. Decide where the record of the originally missing cells comes from and keep using that same record in every iteration. ``` ```hint Copies `np.asarray` hands back the very same object when the input is already a float array. Check every place you write into an array. ``` ### Example ```python leaves = [[1, 2], [1, 3], [4, 2], [4, 3]] proximity_from_leaves(leaves) # [[1. , 0.5, 0.5, 0. ], # [0.5, 1. , 0. , 0.5], # [0.5, 0. , 1. , 0.5], # [0. , 0.5, 0.5, 1. ]] ``` Samples 0 and 1 share leaf 1 in the first tree only, so their proximity is 0.5. Samples 0 and 3 never share a leaf, so theirs is 0. ### Constraints & Assumptions - `X` is 2-D numeric, and missing values are `np.nan`. - `len(y) == X.shape[0]`, and `y` holds discrete class labels. - `tol ≥ 0` and `max_iter ≥ 1`. ### What a Strong Answer Covers - A proximity computation that matches the shared-leaf definition, with the diagonal set to 1. - The full fallback chain in the rough fill: class median, then column median, then `0.0`. - An update that reads only observed values, keeps the current value when the weights sum to zero, and leaves observed entries untouched. - A loop that reuses the original missing mask, refits the forest every iteration, applies the strict `< tol` rule, and returns the correct iteration count. - No mutation of the inputs, and the time and memory cost of the proximity matrix. ### Follow-up Questions - How would you adapt this for categorical features? - The full `n × n` proximity matrix is `O(n²)` memory. How do you scale to large `n`? - Why can computing proximities on the training rows bias the imputation, and what is the fix?

Overview: Implement random forest proximity imputation for a numeric matrix with missing values: a class-aware median fill, then repeated forest fits whose shared-leaf proximities reweight the observed values. It tests careful masking, convergence logic, input immutability and the memory cost of an n by n proximity matrix.

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

Given a float matrix X with NaN entries and class labels y, implement Breiman's RF-Impute. Fill gaps roughly, then repeatedly refine them with random-forest proximities. Return (X_imputed, n_iterations). No function may mutate its inputs.

Implement these functions:

  • proximity_from_leaves(leaves) : leaves is (n_samples, n_trees) . Return P[i, j] = fraction of trees where i and j share a leaf, with diagonal 1.0 .
  • initial_fill(X, y) : each NaN gets the median of observed values in its column for its class. If the class has none, use the column's overall observed median. If the column is fully missing, use 0.0 .
  • impute_step(X_filled, missing_mask, proximity) : each missing (i, j) becomes the mean of observed rows' column- j values, weighted by proximity[i, obs] . If the weights sum to 0, keep the current value. Observed entries never change.
  • rf_impute(X, y, n_estimators=50, max_iter=5, tol=1e-4, random_state=0) : if there is no NaN , return (X.copy(), 0) . Otherwise each iteration fits RandomForestClassifier(n_estimators=n_estimators, random_state=random_state) on the current matrix, builds proximities from rf.apply on that matrix, then applies one impute_step .
  • Stop when the max absolute change over missing entries is strictly < tol , or after max_iter iterations. Return the number of iterations performed.

Example

leaves = [[1, 2], [1, 3], [4, 2], [4, 3]]
proximity_from_leaves(leaves)
# [[1. , 0.5, 0.5, 0. ],
#  [0.5, 1. , 0. , 0.5],
#  [0.5, 0. , 1. , 0.5],
#  [0. , 0.5, 0.5, 1. ]]

Samples 0 and 1 share leaf 1 in the first tree only, so their proximity is 0.5. Samples 0 and 3 never share a leaf, so theirs is 0.

Constraints & Assumptions

  • X is 2-D numeric, and missing values are np.nan .
  • len(y) == X.shape[0] , and y holds discrete class labels.
  • tol ≥ 0 and max_iter ≥ 1 .

What a Strong Answer Covers Guidance

  • A proximity computation that matches the shared-leaf definition, with the diagonal set to 1.
  • The full fallback chain in the rough fill: class median, then column median, then 0.0 .
  • An update that reads only observed values, keeps the current value when the weights sum to zero, and leaves observed entries untouched.
  • A loop that reuses the original missing mask, refits the forest every iteration, applies the strict < tol rule, and returns the correct iteration count.
  • No mutation of the inputs, and the time and memory cost of the proximity matrix.

Follow-up Questions Guidance

  • How would you adapt this for categorical features?
  • The full n × n proximity matrix is O(n²) memory. How do you scale to large n ?
  • Why can computing proximities on the training rows bias the imputation, and what is the fix?