Greedy Collinearity Feature Filter and Atomic CSV Cleaner
Easy · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
Before fitting a linear forecasting model, data engineering workflows typically perform two steps: safe out-of-place CSV scrubbing and greedy screening of collinear predictors. Build both helpers in Python:
def select_uncorrelated_features(
rows: List[Dict[str, float]],
target_col: str,
collinearity_threshold: float = 0.85,
) -> List[str]:
def sanitize_dataset(
src_path: str,
dst_path: str,
required_columns: list[str],
) -> int:
1. Greedy Predictor Screening (select_uncorrelated_features — Automated Judge Entry Point)
rows represents a numeric table as a list of row dictionaries sharing identical keys (str -> float). Screen every predictor column (all keys other than target_col) as follows:
- Ignore any predictor column whose entries are all identical (zero variance makes Pearson correlation undefined). Return
[]immediately ifrowsis empty, iftarget_colitself is constant, or if no non-constant predictor exists. - Measure each remaining predictor's linear strength against
target_colusing the absolute Pearson correlation coefficient|r|. - Order predictors from highest to lowest
|r|againsttarget_col. Resolve exact ties (up to standard floating-point precision) in ascending alphabetical (ASCII) order of column name. - Traverse the sorted predictors in order. Accept a predictor if and only if its absolute Pearson correlation
|r|with each predictor accepted so far satisfies|r| < collinearity_threshold(predictors rejected earlier never block subsequent ones). - Return the accepted column names in acceptance order.
2. Crash-Safe CSV Scrubbing (sanitize_dataset)
- Read CSV lines from
src_pathwithout ever alteringsrc_path(raiseValueErrorifsrc_pathanddst_pathresolve to the same file, if no header line exists, or if any column inrequired_columnsis missing from the header). - Keep the header row plus every data row whose column count matches the header and whose cells in
required_columnsall parse as finite floating-point numbers (rejecting blanks, text,NaN, andinf). - Stage the scrubbed CSV into a sibling temporary file inside
dst_path's directory, flush buffers to storage, and swap it ontodst_pathin one atomic rename (os.replace). Delete any temporary file if an error or interrupt occurs mid-flight sodst_pathis never left half-written. Return how many data rows survived.
Examples
Example 1
Input:
rows = [
{"price": 10, "sqft": 1, "rooms": 2, "age": 8},
{"price": 20, "sqft": 2, "rooms": 4, "age": 2},
{"price": 30, "sqft": 3, "rooms": 5, "age": 6},
{"price": 40, "sqft": 4, "rooms": 9, "age": 0},
]
target_col = "price"
collinearity_threshold = 0.85
Output: ["sqft", "age"]
Walk-through: Against "price", absolute correlations are |r(price, sqft)| = 1.0, |r(price, rooms)| ≈ 0.9648, and |r(price, age)| ≈ 0.7071 (r ≈ -0.7071). "sqft" is chosen first. "rooms" is dropped because |r(rooms, sqft)| ≈ 0.9648 >= 0.85. "age" is then compared against "sqft" (0.7071 < 0.85) and kept.
Example 2
Input:
rows = [
{"load": 4, "wind": -3, "solar": 3, "hydro": 2},
{"load": 2, "wind": -1, "solar": 1, "hydro": -1},
{"load": 0, "wind": 1, "solar": -1, "hydro": 1},
{"load": -2, "wind": 3, "solar": -3, "hydro": -2},
]
target_col = "load"
collinearity_threshold = 0.75
Output: ["solar", "hydro"]
Walk-through: Both "solar" (r = +1.0) and "wind" (r = -1.0) achieve |r| = 1.0 with "load", while "hydro" has |r| ≈ 0.7071. Alphabetical tie-breaking puts "solar" ahead of "wind". "solar" is kept first, "wind" is rejected (|r(wind, solar)| = 1.0 >= 0.75), and "hydro" is kept (|r(hydro, solar)| ≈ 0.7071 < 0.75).
Constraints
0 <= len(rows) <= 10^5(correlations require at least2non-constant observations; smaller or constant inputs return[]).1 <= len(rows[0]) <= 500whenrowsis non-empty, andtarget_colis present in every row dictionary.0.0 <= collinearity_threshold <= 1.0.- All values in
rowsare finiteintorfloatnumbers.
Step-by-step walkthrough
Restate the two utilities and interface details
Data preparation before fitting a linear model needs two building blocks:
sanitize_dataset(src_path, dst_path, required_columns): stream CSV records fromsrc_path, skip malformed lines or rows lacking finite floats inrequired_columns, and publish the scrubbed CSV todst_pathatomically (another reader sees either the previousdst_pathor the finished replacement, never a truncated file, whilesrc_pathstays untouched). Return how many data rows survived.select_uncorrelated_features(rows, target_col, collinearity_threshold=0.85): order predictor columns from strongest to weakest|r|(absolute Pearson correlation) againsttarget_colwith alphabetical tie-breaking, then accept a predictor only if its|r|against every predictor accepted so far satisfies|r| < collinearity_threshold.
In
starter.py, the automated judge testsselect_uncorrelated_featuresonrows: List[Dict[str, float]](a list of row dictionaries), and we includesanitize_datasetalongside it as a complete solution.Three clean rules keep every boundary case deterministic:
- Constant columns have zero standard deviation (leaving
r = 0 / 0undefined); constant predictors are ignored, and a constant target returns[]. - Rounding
|r|to12decimal places prevents10^-16floating-point drift from disturbing exact ties or slipping pastcollinearity_threshold. - In
sanitize_dataset, every cell listed inrequired_columnsmust parse as a finitefloat(rejecting"","abc","NaN", and"inf"), while non-required columns pass through unchanged.
Understand Pearson correlation and why we precompute one matrix
Pearson correlation (
r) measures how closely two numeric columnsxandyfollow a straight line:mean_x = sum(x) / N, mean_y = sum(y) / N r(x, y) = sum((x_i - mean_x) * (y_i - mean_y)) ----------------------------------------------------------- sqrt( sum((x_i - mean_x)^2) * sum((y_i - mean_y)^2) )ralways lies between-1and+1. A correlation of-0.95meansymoves in the exact opposite direction ofx— which carries the same redundant linear information as+0.95! That is why we take the absolute value|r|both when ranking against the target and when screening pairs of predictors.Rather than recomputing
O(N)dot products inside nested loops, we stack the target and allKvalid candidate features into a(K + 1) x Narray and callnp.corrcoefonce:all_series index: 0 (price) 1 (sqft) 2 (rooms) 3 (age) +------------+-------------+-------------+-------------+ 0 (price) | 1.00 | |r(p, sqft)|| |r(p, rooms)|| |r(p, age)| | <-- row 0 ranks features! 1 (sqft) | |r(sqft,p)|| 1.00 | |r(s, rooms)|| |r(s, age)| | 2 (rooms) ||r(rooms,p)|| |r(rooms,s)|| 1.00 | |r(r, age)| | <-- pairwise lookups! 3 (age) | |r(age, p)|| |r(age, s)| | |r(age, r)| | 1.00 | +------------+-------------+-------------+-------------+After this single matrix computation, every correlation check in our greedy filter is an
O(1)array lookup!Handle constant columns and floating-point tie noise
Two numerical traps trip up many implementations:
- Constant columns (
min(values) == max(values)): When all entries in a column are equal, its denominator inr(x, y)is0, producingNaN. BecauseNaN >= thresholdandNaN < thresholdboth evaluate toFalse, leavingNaNin the matrix silently corrupts sorting and filtering. Note thatmin(values) == max(values)is exact, whereasnp.std([0.1, 0.1, 0.1]) == 0isFalse(~1.4e-17) due to binary float rounding! We also return[]early ifcandidate_namesis empty sonp.corrcoefalways receives at least 2 rows and always returns a 2-D matrix. - Tiny float noise on ties and thresholds: A column
aand its scaled copy3 * a + 5have mathematical correlation1.0, yet float division can yield0.9999999999999999. Without rounding,0.9999999999999999 < 1.0would wrongly keep an exact duplicate atthreshold = 1.0, and tiny1e-16differences would break ties arbitrarily instead of alphabetically. Rounding|r|to12decimal places (np.round(..., 12)) eliminates1e-16noise cleanly.
def column_values(rows: List[Dict[str, float]], col_name: str) -> List[float]: """Extract one named column from row dictionaries as a list of floats.""" values = [] for row in rows: values.append(float(row[col_name])) return values def is_constant(values: List[float]) -> bool: """Exact zero-variance check without floating-point mean rounding errors.""" return min(values) == max(values)- Constant columns (
Rank candidates and run the greedy collinearity filter
Python compares tuples from left to right. If we represent each candidate as
(-target_corr, col_name, matrix_idx), calling.sort()puts the largesttarget_corrfirst (since-1.0 < -0.9648) and automatically breaks equal-target_corrties in ascending alphabetical order ofcol_name("solar" < "wind").Next, we walk through
ranked_candidatesin sorted order:- The very first candidate is always selected because
selected_indicesis initially empty. - Each later candidate is compared only against
selected_indices(predictors we actually kept — a dropped predictor never blocks future candidates!). - Because the requirement is strictly less than (
|r| < collinearity_threshold), any pair withabs_corr_matrix[candidate_idx, selected_idx] >= collinearity_thresholdmarks the candidate redundant.
def greedy_filter( candidate_names: List[str], abs_corr_matrix: np.ndarray, collinearity_threshold: float, ) -> List[str]: ranked_candidates = [] for idx, col_name in enumerate(candidate_names): matrix_idx = idx + 1 target_corr = float(abs_corr_matrix[0, matrix_idx]) ranked_candidates.append((-target_corr, col_name, matrix_idx)) ranked_candidates.sort() selected_names = [] selected_indices = [] for _, col_name, candidate_idx in ranked_candidates: is_redundant = False for selected_idx in selected_indices: if abs_corr_matrix[candidate_idx, selected_idx] >= collinearity_threshold: is_redundant = True break if not is_redundant: selected_names.append(col_name) selected_indices.append(candidate_idx) return selected_names- The very first candidate is always selected because
Walk through Example 1 step by step
In Example 1,
price = [10, 20, 30, 40],sqft = [1, 2, 3, 4],rooms = [2, 4, 5, 9],age = [8, 2, 6, 0], andcollinearity_threshold = 0.85:Pairwise |r| values: |r(price, sqft)| = 1.0, |r(price, rooms)| = 0.9648, |r(price, age)| = 0.7071 |r(sqft, rooms)| = 0.9648 |r(sqft, age)| = 0.7071 Sorted candidates: 1. (-1.0, 'sqft', 1) -> selected is [], keep 'sqft' -> selected = ['sqft'] 2. (-0.9648, 'rooms', 2) -> |r(rooms, sqft)| = 0.9648 >= 0.85 -> DROP 3. (-0.7071, 'age', 3) -> |r(age, sqft)| = 0.7071 < 0.85 -> KEEP -> selected = ['sqft', 'age']Notice
ageis never compared againstroomsbecauseroomswas dropped. Output:['sqft', 'age'].Build the atomic CSV cleaner: temp file + fsync + os.replace
Why is
open(dst_path, "w")dangerous in a data pipeline? Because"w"immediately wipesdst_pathto0bytes, and if the process crashes or runs out of disk halfway through row500,000, downstream readers see a truncated, corrupted CSV!The standard POSIX pattern for an atomic file update stages everything into a hidden sibling file first, then swaps directory pointers in one instant:
src_path (opened read-only, streamed 1 row at a time) | v validate header + finite floats in required_columns dst_dir/.tmp-8f3k2.csv <-- 1. chmod 0644, write rows, flush() + os.fsync() | | 2. os.replace(tmp, dst_path) [atomic on same filesystem!] v dst_path (if step 1 fails, remove .tmp file; old dst_path is untouched)Every line in that recipe solves a real production failure mode:
- Same directory (
dir=dst_dir):os.replacecan only atomically rename within the same filesystem;/tmpis often a separate mount whereos.replaceraisesOSError. delete=False+try / except BaseException: keeps the temp file alive after closing soos.replacecan rename it, while guaranteeing.tmp-*is deleted on any error (evenKeyboardInterrupt).os.chmod(..., 0o644)+os.fsync:NamedTemporaryFiledefaults to0600(owner-only), which would lock out group readers after rename, andfsyncforces data out of OS RAM buffers onto physical storage before replacingdst_path.
- Same directory (
Code sanitize_dataset
def is_finite_float(text: str) -> bool: """Return True if text parses as a finite float (rejecting '', 'NaN', 'inf', 'abc').""" try: value = float(text) except ValueError: return False return math.isfinite(value) def row_is_valid(row: List[str], expected_width: int, required_positions: List[int]) -> bool: """Keep a row only if its column count matches the header and required cells are finite floats.""" if len(row) != expected_width: return False for pos in required_positions: if not is_finite_float(row[pos]): return False return True def sanitize_dataset(src_path: str, dst_path: str, required_columns: list[str]) -> int: # Guard against overwriting the source file when src_path and dst_path point to the same inode. if os.path.exists(dst_path) and os.path.samefile(src_path, dst_path): raise ValueError("dst_path must be different from src_path") with open(src_path, "r", encoding="utf-8", newline="") as src_file: reader = csv.reader(src_file) header = next(reader, None) if header is None: raise ValueError("source file has no header row") # Map each required column name to its 0-based index in every CSV row. required_positions = [] for col_name in required_columns: if col_name not in header: raise ValueError(f"missing required column: {col_name}") required_positions.append(header.index(col_name)) # Place the temp file in dst_path's directory so os.replace stays on the same # filesystem and remains a single atomic POSIX directory rename. dst_dir = os.path.dirname(os.path.abspath(dst_path)) tmp_file = tempfile.NamedTemporaryFile( "w", encoding="utf-8", newline="", dir=dst_dir, prefix=".tmp-", suffix=".csv", delete=False, ) kept_rows = 0 try: # NamedTemporaryFile defaults to owner-only permissions (0600); widen to 0644. os.chmod(tmp_file.name, 0o644) with tmp_file: writer = csv.writer(tmp_file) writer.writerow(header) for row in reader: if row_is_valid(row, len(header), required_positions): writer.writerow(row) kept_rows += 1 # Flush Python buffers and force OS disk write before publishing via rename. tmp_file.flush() os.fsync(tmp_file.fileno()) os.replace(tmp_file.name, dst_path) except BaseException: # Clean up any partial temp file on errors or interrupts; dst_path stays untouched. if os.path.exists(tmp_file.name): os.remove(tmp_file.name) raise return kept_rowsComplete solution
from typing import Any, Dict, List, Optional, Set, Tuple import csv import math import os import tempfile import numpy as np # ---------- Part 1: atomic, non-destructive CSV cleaning ---------- def is_finite_float(text: str) -> bool: """Return True if text parses as a finite float (rejecting '', 'NaN', 'inf', 'abc').""" try: value = float(text) except ValueError: return False return math.isfinite(value) def row_is_valid(row: List[str], expected_width: int, required_positions: List[int]) -> bool: """Keep a row only if its column count matches the header and required cells are finite floats.""" if len(row) != expected_width: return False for pos in required_positions: if not is_finite_float(row[pos]): return False return True def sanitize_dataset(src_path: str, dst_path: str, required_columns: list[str]) -> int: # Guard against overwriting the source file when src_path and dst_path point to the same inode. if os.path.exists(dst_path) and os.path.samefile(src_path, dst_path): raise ValueError("dst_path must be different from src_path") with open(src_path, "r", encoding="utf-8", newline="") as src_file: reader = csv.reader(src_file) header = next(reader, None) if header is None: raise ValueError("source file has no header row") # Map each required column name to its 0-based index in every CSV row. required_positions = [] for col_name in required_columns: if col_name not in header: raise ValueError(f"missing required column: {col_name}") required_positions.append(header.index(col_name)) # Place the temp file in dst_path's directory so os.replace stays on the same # filesystem and remains a single atomic POSIX directory rename. dst_dir = os.path.dirname(os.path.abspath(dst_path)) tmp_file = tempfile.NamedTemporaryFile( "w", encoding="utf-8", newline="", dir=dst_dir, prefix=".tmp-", suffix=".csv", delete=False, ) kept_rows = 0 try: # NamedTemporaryFile defaults to owner-only permissions (0600); widen to 0644. os.chmod(tmp_file.name, 0o644) with tmp_file: writer = csv.writer(tmp_file) writer.writerow(header) for row in reader: if row_is_valid(row, len(header), required_positions): writer.writerow(row) kept_rows += 1 # Flush Python buffers and force OS disk write before publishing via rename. tmp_file.flush() os.fsync(tmp_file.fileno()) os.replace(tmp_file.name, dst_path) except BaseException: # Clean up any partial temp file on errors or interrupts; dst_path stays untouched. if os.path.exists(tmp_file.name): os.remove(tmp_file.name) raise return kept_rows # ---------- Part 2: greedy collinearity filter ---------- def column_values(rows: List[Dict[str, float]], col_name: str) -> List[float]: """Extract one named column from row dictionaries as a list of floats.""" values = [] for row in rows: values.append(float(row[col_name])) return values def is_constant(values: List[float]) -> bool: """Exact zero-variance check without floating-point mean rounding errors.""" return min(values) == max(values) def select_uncorrelated_features(rows: List[Dict[str, float]], target_col: str, collinearity_threshold: float = 0.85) -> List[str]: if not rows: return [] target_values = column_values(rows, target_col) if is_constant(target_values): # Pearson correlation divides by standard deviation, so a constant target has none. return [] # Phase 1: collect non-constant candidate features into a 2D series table. # all_series[0] is target_values; all_series[i + 1] corresponds to candidate_names[i]. candidate_names = [] all_series = [target_values] for col_name in rows[0]: if col_name == target_col: continue values = column_values(rows, col_name) if not is_constant(values): candidate_names.append(col_name) all_series.append(values) if not candidate_names: return [] # Phase 2: compute the (K + 1) x (K + 1) |Pearson correlation| matrix once upfront. # Rounding to 12 decimals strips ~1e-16 float noise so mathematically equal |r| values # tie cleanly by column name and |r| == 1.0 never slips under threshold 1.0 as 0.9999999999999999. abs_corr_matrix = np.round(np.abs(np.corrcoef(np.array(all_series))), 12) # Phase 3: rank candidates by descending |corr with target|, breaking ties alphabetically. # Negating target_corr lets a single ascending tuple sort handle both rules at once. ranked_candidates = [] for idx, col_name in enumerate(candidate_names): matrix_idx = idx + 1 target_corr = float(abs_corr_matrix[0, matrix_idx]) ranked_candidates.append((-target_corr, col_name, matrix_idx)) ranked_candidates.sort() # Phase 4: greedily keep a candidate only if its |corr| with EVERY already-selected # feature is strictly less than collinearity_threshold (so >= disqualifies it). selected_names = [] selected_indices = [] for _, col_name, candidate_idx in ranked_candidates: is_redundant = False for selected_idx in selected_indices: if abs_corr_matrix[candidate_idx, selected_idx] >= collinearity_threshold: is_redundant = True break if not is_redundant: selected_names.append(col_name) selected_indices.append(candidate_idx) return selected_names✅ Submit now — all tests should pass.
Intuition & how it works
Think of select_uncorrelated_features as hiring analysts for a forecasting committee: you score every applicant by Pearson correlation (a number from -1 to +1 measuring how closely two numeric variables track a straight line) with the outcome target_col, hire the strongest predictor first, and skip any later applicant who is a near-clone of someone already on the committee — preventing multicollinearity (when two or more input features carry nearly the same linear signal, destabilizing regression weights). Similarly, think of sanitize_dataset as replacing a live reference manual on a shared shelf using an atomic write (an all-or-nothing file update): you draft and proofread the clean copy into a sibling temporary file, flush it to disk, and swap it into place with a single os.replace rename so readers never see a half-written file.
Naive implementations stumble on both tasks. Opening dst_path directly with "w" immediately truncates any existing file, so a crash mid-way destroys the old output and leaves corrupted CSV lines behind. In feature screening, recomputing correlations from raw rows inside the greedy loop wastes O(N) work per check, and forgetting to strip constant columns or tiny floating-point rounding noise (0.9999999999999999 vs 1.0) breaks ties randomly and lets duplicate columns slip past threshold = 1.0.
Walk through Example 1 (price = [10, 20, 30, 40], sqft = [1, 2, 3, 4], rooms = [2, 4, 5, 9], age = [8, 2, 6, 0], threshold = 0.85):
- Upfront
|r|withprice:sqfthas1.0,roomshas0.9648, andagehas0.7071(r = -0.7071), giving rank order['sqft', 'rooms', 'age']. sqftis first, so it joinsselected_names = ['sqft'].roomshas|r(rooms, sqft)| = 0.9648 >= 0.85, so it is discarded;ageis then checked only againstsqft(0.7071 < 0.85) and kept, returning['sqft', 'age'].
Complexity
Let N be the number of rows and M be the number of candidate feature columns (K <= M non-constant features).
- Feature selection time: O(N * M^2), because extracting columns and checking
min == maxscans allN * Mcells once (O(N * M)),np.corrcoefmultiplies a(K + 1) x Nmatrix by its transpose inO(N * K^2)(<= O(N * M^2)), sortingKcandidates takesO(M log M), and the greedy pass performs at mostK * (K - 1) / 2O(1)matrix lookups (O(M^2)). - Feature selection space: O(N * M + M^2), because
all_seriesholds up to(M + 1) * Nfloats andabs_corr_matrixholds(K + 1)^2floats. - File cleaning time: O(B) where
Bis the byte size ofsrc_path, becausecsv.readerandcsv.writerinspect and write each row once in a single linear pass. - File cleaning space: O(L) RAM and O(B) temporary disk where
Lis the length of a single CSV row, because streaming viacsv.readerholds only one row in memory at a time while staging one cleaned copy ondst_path's filesystem.
Edge cases
- Exact ties in
|r|withtarget_col: broken deterministically in alphabetical (ASCII/ Unicode code-point) order via the tuple(-target_corr, col_name, matrix_idx). - Strong negative correlations (
r = -1.0):np.abstreats-1.0identically to+1.0both when ranking againsttarget_coland when blocking redundant pairs. - Pairwise
|r|equal tocollinearity_threshold: rejected via>=, matching the strict requirement|r| < collinearity_threshold. - Boundary thresholds
0.0and1.0: at0.0, the top-ranked feature is still added (sinceselected_indicesstarts empty) and every subsequent candidate fails|r| >= 0.0; at1.0, rounding to12decimals ensures exact linear copies (|r| = 1.0) are still dropped. - Constant target, constant features, or no valid features: constant features (
min == max) are skipped before callingnp.corrcoef, and an empty table, constant target, or table with zero non-constant features immediately returns[]. - CSV hazards (
NaN,inf, wrong column count,src_path == dst_path):math.isfinite(float(text))rejects"NaN"and"inf",len(row) != expected_widthdrops malformed rows, andos.path.samefileraisesValueErrorbefore opening any file for writing.
Common mistakes
- Forgetting
np.abswhen ranking or filtering: in Example 2,wind = [-3, -1, 1, 3]hasr = -1.0withload = [4, 2, 0, -2]; sorting by signedrputs a perfect predictor dead last. - Comparing a candidate against dropped features instead of only
selected_indices: ifsqftdropsrooms,roomsis not in the model and must never blockage. - Using
<=instead of<oncollinearity_threshold(or skippingnp.round): keeps features sitting right on the threshold, or lets scaled duplicates with float correlation0.9999999999999999pass< 1.0. - Creating the temp file in
/tmpinstead ofdst_dir:/tmpis frequently a separatetmpfsmount, causingos.replaceto fail withEXDEV(Invalid cross-device link). - Leaving default
0600permissions or skipping cleanup on exceptions:NamedTemporaryFilecreates owner-only files unlessos.chmodis called, anddelete=Falseleaks.tmp-*files on errors unless wrapped intry / except BaseException.
Alternative approaches
- Using
pandasdirectly: When input arrives as apd.DataFrame, drop constant columns viadf.nunique() > 1, computeabs_corr = df.corr(method="pearson").abs().round(12), and run the exact same greedy loop; forsanitize_dataset, iteratepd.read_csv(src_path, chunksize=50_000)into the sameNamedTemporaryFile+os.replacewrapper. - On-demand dot products when
Mis huge and few features survive: Z-score normalize each candidate column once (z = (x - mean) / std,O(N * M)total), sort by|z_target . z_j| / N, and compute pairwise dot products|z_cand . z_sel| / Nonly against features that actually enterselected_indices, reducingO(N * M^2)toO(N * M * S)whenS << Mfeatures are selected.
Follow-up questions
- How would you process multi-gigabyte CSV logs that are far larger than system memory, and how could you parallelize that throughput safely? Our
csv.reader/csv.writerimplementation already streams one line at a time inO(longest_row)RAM, so a multi-gigabyte file will not exhaust memory as long asdst_dirhas enough free disk space for the staged temporary file (whereaspd.read_csv(src_path)withoutchunksizewould crash withMemoryError). To speed up wall-clock throughput, splitsrc_pathinto byte-offset ranges aligned to newline boundaries (assuming no multi-line quoted strings), validate ranges in parallel worker processes writing separate.tmp-part-kfiles, concatenate the parts in order into one staged file,fsync, and publish with a singleos.replace. - What kind of multi-feature redundancy slips past pairwise correlation checks, and how do Variance Inflation Factor (VIF) or Principal Component Analysis (PCA) catch it? Pairwise correlation only inspects two features at a time, so if
x1andx2are independent standard normals andx3 = x1 + x2, then|corr(x3, x1)| = |corr(x3, x2)| = 1 / sqrt(2) ≈ 0.707 < 0.85— all three pass the filter even thoughx3is a 100% redundant sum ofx1andx2! Variance Inflation Factor (VIF) (defined as1 / (1 - R_j^2), whereR_j^2is theR^2from regressing featurejagainst all other features simultaneously) catches multi-way linear combinations (R_3^2 = 1givesVIF = infinity), and you iteratively drop the highest-VIF feature until all VIFs sit below5or10. Principal Component Analysis (PCA) (an orthogonal linear transformation that projects correlated features onto uncorrelated axes ordered by variance explained) removes collinearity completely by dropping near-zero-variance components, trading away individual column interpretability. - When concurrent workers in a distributed job queue target the same output path, how do you prevent stale overwrites and write races? Unique
.tmp-*filenames plusos.replaceprevent corrupt interleaved bytes on POSIX filesystems, but two concurrent workers still suffer a "last writer wins" race where a slow retry from an older run overwrites fresher data. If the transformation is idempotent (running it multiple times on the same immutable input produces byte-for-byte identical output), duplicate execution is harmless; otherwise, write each job's output to an immutable versioned path (dst/run_id=.../part-*.parquet) and update a single metadata pointer or transactional table log (such as Delta Lake or Iceberg) using optimistic concurrency control. If you must coordinate a single mutable path across machines, acquire a distributed lock backed by a fencing token (a monotonically increasing integer issued with each lock grant that storage checks to reject stale writes from paused workers).
Follow-up questions
- How would you process multi-gigabyte CSV logs that are far larger than system memory, and how could you parallelize that throughput safely?
- What kind of multi-feature redundancy slips past pairwise correlation checks, and how do Variance Inflation Factor (VIF) or Principal Component Analysis (PCA) catch it?
- When concurrent workers in a distributed job queue target the same output path, how do you prevent stale overwrites and write races?
Similar questions
- Time-Zoned Event Deduplication, Retention, and ARPU Pipeline
- Memory-Bounded CSV Ingestion, Cleaning, and Smoothing
- Clean, Winsorize, and Scale Tabular Predictors for Regression
- Ring Bit Toggles Under Stepping Markers
- Auditing, Tuning, and Serving a Forecasting Pipeline
- Joint OLS R-Squared Bounds from Single-Feature Scores
More Voleon interview questions
- Auditing, Tuning, and Serving a Forecasting Pipeline Medium
- Joint OLS R-Squared Bounds from Single-Feature Scores Medium
- Queen Line-of-Sight Queries With Obstacles Medium Pro
- Regression Pipeline Design for Skewed Customer Revenue Hard Pro
- Sparse Matrix Arithmetic with Shape Validation Medium Pro
- Diagnosing Train and Test Loss Across Regularization and Sample Size Medium Pro
- Keep Words with Non-Unique Anagram Signatures Medium Pro
- Limit Order Book and Participation-Rate Execution Simulator Medium Pro
- Markov Chains, Rotated OLS Estimators, and Parallel Coin Stopping Times Easy Pro
- Verify Binary Strings Under a Prefix Grammar Medium Pro