Feature Transformation Functions
Thirty original Python problems on fitted feature schemas, robust and power transforms, categorical contrasts, ordered target history, exact feature dependence, temporal information support and nonlinear bases. Keep training evidence and transform-only observations distinct.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Impute from the most specific supported training population
Write
hierarchy_fill(train,queries,fallback). Rows are[string_group,string_subgroup,finite_value_or_None]. Fit present TRAIN medians only: exact (group,subgroup), then group, then all train, then finite fallback. Even medians use midpoints. For each query return[value,source], source"observed","pair","group","global"or"default". Keep present query values, including zero. No mutation.2.Fit missing-indicator columns before transforming new rows
Write
missing_schema(train,other,width). Rectangular finite/Nonerows have the supplied nonnegative width. Select columns having at least oneNonein TRAIN, in column order. Return [selected_columns,other_rows_with_0_or_1_missing_indicators_appended_for_those_columns]. Keep original other values. Missingness first seen in other creates no column. Empty train selects none. No mutation.3.Select features using supported training population variance
Write
variance_columns(train,other,width,threshold). Finite/Nonerectangular rows have width>=0; threshold>=0 finite. Per column use present TRAIN values only. Keep columns with at least two present values AND population variance STRICTLY greater than threshold. Return[kept_indices,projected_other_rows]in original column order. No support is not zero evidence. No mutation.4.Fit linear quartiles and clip only transformed robust scores
Write
robust_clip(train,values,bound), finite/Nonelists, bound>=0. Fit median and IQR=Q(.75)-Q(.25)from present train only. Linear quantileQ(q)interpolates sorted positions at (n-1)*q. Use scale=1 if IQR=0; no present train uses center=0,scale=1. Return[center,scale,clipped_(x-center)/scale_values], preservingNone, clipping to[-bound,bound]. No mutation.5.Construct radial features around supplied centers
Write
radial_features(rows,centers,gamma). Finite numeric vectors share one width, possibly zero; gamma>=0 finite. Output for row x and center c is exp(-gamma*sum((x_j-c_j)**2)). Preserve row and center order. Use squared distance, no square root or center refitting. Empty centers produce one empty vector per row. No mutation.6.Keep both signs and limiting power-transform branches
Write
signed_power(values,lmbda), |x|<=1e4 orNone, -2<=lmbda<=4. For x>=0 return ((1+x)**lmbda-1)/lmbda, usingln(1+x)at lmbda=0. For x<0 return -((1-x)**(2-lmbda)-1)/(2-lmbda), using -ln(1-x)at lmbda=2. PreserveNone/order and use numerically stable log1p/expm1 evaluation near limits. No mutation.7.Choose a supplied Box-Cox power with the Jacobian term
Write
boxcox_choice(values,candidates). 0<=n<=50 positive x in[1e-3,1e3]; <=32 lambdas in[-2,2]. y=(x**l-1)/l, orln(x)at l=0. Score=-(n/2)*ln(population_variance(y))+(l-1)*sum(ln(x)). Return[chosen_lambda,transformed_values], maximizing score; scores within 1e-10 of max tie toward smaller lambda. Empty/constant values or no candidates returnNone. No mutation.8.Keep periodic harmonic feature columns in declared order
Write
cyclic_features(times,periods,harmonics). Times finite, periods positive finite in supplied order, harmonics integer 0..4. For each time outputsin(2*pi*h*t/period),cos(same_angle), for each period then h=1..harmonics. Do not sort periods, swap sine/cosine or drop repeated periods. Zero harmonics gives empty rows. No mutation.9.Preserve supplied knot order in a truncated linear basis
Write
hinge_features(values,knots), finite numeric lists. For each x return[1,x]followed bymax(0,x-knot)for EVERY knot in supplied order. Repeated knots create repeated columns; equality creates zero. Knots are fixed, never refit or sorted. Empty knots retain[1,x]. No mutation.10.Enumerate a complete graded interaction feature basis
Write
interaction_basis(rows,width,degree,bias). Finite rows have width in 0..4; degree in 0..4, bias bool. Enumerate exponent tuples e>=0 withsum(e)<=degree, sorted by (sum(e),tuple(e)); include all-zero tuple only if bias. Return[exponent_lists,expanded_rows], where feature=product(x_j**e_j). Cross terms ARE included; product over zero coordinates is 1. No mutation.11.Keep frequent rare unseen and missing categories distinct
Write
category_states(train,values,minimum,limit). String/Nonelists; minimum>=1,limit>=0 integers. Count present train categories. Keep at most limit categories with count>=minimum, sorted by (-count,name), assigning IDs 0..k-1. Other observed train categories map to k, unseen strings to k+1,Noneto k+2. Return[kept_names,encoded_values]. Never fit from values. No mutation.12.Reserve one smoothed frequency bucket for unseen categories
Write
smoothed_frequency(train,values,alpha). String lists, alpha>0 finite. Let N=len(train), K=distinct train count. Encode x as (train_count(x)+alpha)/(N+alpha*(K+1)), reserving ONE extra unseen bucket. Known and unseen values share this denominator; repeated query values do not alter it. Empty train encodes any query as 1. Return values in query order. No mutation.13.Encode targets from earlier permutation positions only
Write
ordered_targets(rows,order,prior,alpha). rows are[string_category,finite_target]; order is a permutation of all row indices; prior finite, alpha>0. Visit order. Before adding a row, encode its category as (earlier_category_target_sum+alpha*prior)/(earlier_category_count+alpha). Then add its target. Return encodings in ORIGINAL row order. No current/future targets or mutation.14.Build an explicitly scaled Helmert-style contrast matrix
Write
helmert_features(values,levels). levels is a nonempty unique string list of length K, defining order. For known level at index r, column j=0..K-2 is 1/(j+1) if r<=j, -1 if r=j+1, otherwise 0. Unknown strings returnNone. Return one vector orNoneper value; known K=1 gives []. Use this explicit sign/scale convention, without sorting levels. No mutation.15.Serialize categorical crosses with UTF-8 length prefixes
Write
cross_keys(rows), each row a list of strings orNone. EncodeNoneas"N"; encode a string s as"S"+decimal_UTF8_byte_length(s)+":"+s. Concatenate encoded fields with no added separator; an empty row gives "". Return one key per row. Do not use character count, delimiter joining, case folding or Unicode normalization. No mutation.16.Separate unknown levels from ordinal threshold vectors
Write
ordinal_features(values,levels). levels is a unique string list in declared increasing ordinal order, possibly empty. Known level rank r maps to[int(r>j) for j=0..K-2]. Unknown strings returnNone. Keep values/level order; known K=1 gives [], while no declared levels makes every value unknown. No mutation.17.Deduplicate columns using training evidence only
Write
unique_columns(train,other,width). Finite/Nonerectangular rows have width>=0. Two columns duplicate only if their entire TRAIN value sequences match, including missing positions. Keep the earliest column of each matching sequence. If train is empty, keep all columns because there is no evidence. Return[kept_indices,projected_other_rows]. Never fit on other values. No mutation.18.Retain earliest features independent of an intercept
Write
affine_columns(train,other,width). At most 12 finite train rows, width 0..8; other rows share width. Start with an intercept column of ones. In column order retain a column iff it raises exact rank of intercept and previously kept columns. Interpret decimals exactly, without tolerance. Return[kept_indices,projected_other_rows]; empty train returnsNone. No mutation.19.Solve a lower-triangular feature map forward
Write
decorrelate(rows,mean,lower). Finite rows/mean have width p>=0. lower is supplied p-by-p lower triangular with positive diagonal, such as a known covariance Cholesky factor. For each x return z solving lower*z=x-mean by forward substitution. Do not multiply by lower, solve its transpose or refit statistics. Zero-width rows remain empty. No mutation.20.Coalesce sparse coordinates before unit normalization
Write
sparse_unit(rows). Each row lists[nonnegative_integer_column,finite_value]pairs, possibly repeated/unsorted. Sum duplicate coordinates EXACTLY as decimals, drop resulting zeros, then divide retained values by the vector L2 norm. Return sorted[column,normalized_value]pairs per row. A zero vector gives []. Compute the norm AFTER duplicate summation. No mutation.21.Replace compositional zeros before centered log ratios
Write
composition_features(rows,delta). Nonnegative finite rows; delta>0 with delta*row_length<1. For a nonzero row with z zeros, replace zeros by delta and rescale positives to sum 1-z*delta. Return[closed_row,centered_logs],centered_logs[i]=ln(closed_i)-mean(ln(closed)). Empty/all-zero row returnsNone. Without zeros simply normalize to sum one. No mutation.22.Separate within-group deviation from between-group context
Write
within_between(train,queries). Rows[string_group,finite_value]. Fit global mean and each group mean from TRAIN. For query[g,x]return[x-group_mean,group_mean-global_mean]; unseen g uses global mean. Preserve query order. Empty train returnsNone, even with empty queries. These two features sum to x-global_mean. No mutation.23.Build decayed features from available events
Write
available_decay(events,queries,window,half_life). Events [string_key,integer_event_time,integer_available_time,finite_value], available>=event. Queries[key,t], integer t; window>0 integer,half_life>0 finite. Include same-key events with t-window<=event_time<t ANDavailable_time<=t. Return[sum(value*2**(-(t-event_time)/half_life)),included_count]per query. Repeats count. No mutation.24.Lag within entities without skipping missing values
Write
panel_differences(rows,lag). Rows[string_entity,integer_time,finite_value_or_None]have unique (entity,time); lag>=1 integer. Sort each entity by time. For each row subtract its lag-th previous OBSERVATION value; returnNoneif that position is absent or either value isNone. Missing observations still occupy positions. Return results in source order, with no time interpolation or mutation.25.Integrate historical step features over a whole query window
Write
step_means(events,queries). Events[string_key,integer_time,finite_value]set a right-continuous step value; same-key/time ties use LAST arrival. Queries[key,start,end], integer start<end. Return average value over [start,end), weighted by duration. If no same-key event at/before start, returnNone. Updates at end contribute nothing. Input may be unsorted. No mutation.26.Fill a missing run only with nearby observed endpoints
Write
bounded_fill(times,values,max_gap). times strictly increasing integers; matching values finite orNone;max_gap>=0 integer. For eachNoneuse nearest observed endpoints on both sides. Fill by linear time interpolation ONLY if endpoint time difference<=max_gap. Otherwise keepNone. Do not extrapolate, interpolate by row count or let filled values become new endpoints. No mutation.27.Construct Bernstein features including binomial multiplicity
Write
bernstein_features(values,degree). Each finite x in[0,1], degree integer 0..8. Return[binomial(degree,j)*x**j*(1-x)**(degree-j) for j=0..degree]per x. Keep increasing j order. Use the convention 0**0=1, so endpoints and degree zero remain defined. No refitting or mutation.28.Evaluate clamped splines with endpoint support
Write
spline_features(values,knots,degree). Finite values; degree 0..3; valid nondecreasing clamped knots (endpoints repeated degree+1, first<last). Return alllen(knots)-degree-1 Cox-de Boor basis values per x, using the starter docstring recurrence. Zero-denominator terms are zero. Outside[first,last]all zero; x=last has only the last basis equal to one. No mutation.29.Recover original-coordinate coefficients of a linear score
Write
raw_score(matrix,offset,weights,bias). Finite matrix is q-by-p with q>=1,p>=0, offset/weights length q. A transformed row is z=matrix*x+offset and its score isdot(weights,z)+bias. Return[raw_weights,raw_bias]giving exactly the same score directly on x. Preserve original input-coordinate order. Do not confuse matrix orientation or omit offset. No mutation.30.Recover intervals from saturated clipped features
Write
clip_preimages(values,center,scale,bound). Finite center, scale>0,bound>0; each value z isNoneor in[-bound,bound]. Forward map is clip((x-center)/scale,-bound,bound). Return its raw-x preimage[lo,hi]per observed z, usingNonefor an unbounded interval end. Interior z is one exact point; saturation endpoints are intervals. Missing z returnsNone. No mutation.