Evaluation Utilities
Original AI/ML Engineer coding practice on evaluation weights, thresholds, calibration, paired comparisons, missing outcomes, uncertainty summaries and model-selection gates. Use Python standard-library code without mutating inputs.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Count weighted outcomes and missing predictions
Write
weighted_outcomes(labels, predictions, weights). Labels are 0/1; predictions are 0/1 orNone. Lists have equal length and weights are nonnegative. Return a dict with tp, fp, fn, tn and missing weighted totals. ANoneprediction contributes only to missing, regardless of its label. Include every key even for empty input.2.Sweep complete score-tie groups
Write
threshold_counts(labels, scores)for equally long lists of binary labels and finite scores. At every distinct observed score t, classify scores >= t as positive. Return[t,tp,fp,fn,tn]rows with t decreasing. Include all equal scores together and no synthetic thresholds. Empty input returns [].3.Measure pairwise AUC with half-credit ties
Write
pair_auc(labels, scores)for binary labels and equally long finite scores. Compare every positive-labeled score with every negative-labeled score: credit 1 if the positive is larger, 0.5 if equal, otherwise 0. Return mean credit across these pairs, orNoneif either class is absent. Do not threshold scores.4.Score a full multiclass probability vector
Write
multiclass_brier(labels, probabilities). Each row is a probability vector of the same positive width, and each label is a valid class index. For each row sum (p[j]-indicator(j==label)) squared over all classes, then average those sums. Do not divide by class count or by 2. Empty input returns 0.0.5.Clip probabilities before binary log loss
Write
clipped_log_loss(labels, probabilities, epsilon). Lists have equal length, labels are 0/1, probabilities lie in[0,1], and 0 < epsilon < 0.5. Clip each probability to[epsilon,1-epsilon], then average -log(p)for label 1 and -log(1-p)for label 0, using natural logs. Empty input returns 0.0.6.Preserve calibration bin boundaries
Write
calibration_totals(labels, probabilities, edges). Labels are 0/1 and probabilities are in[0,1]. Strictly increasing edges start at 0 and end at 1. Each bin includes its left edge and excludes its right edge, except the final bin includes 1. Return[count,sum_probability,positive_count]for every bin, retaining empty bins.7.Weight calibration gaps by observation count
Write
calibration_gap(bins), where each bin is[count,sum_confidence,correct_count]. Counts are nonnegative, sums are consistent with counts, and a zero-count bin has zero sums. Return sum(abs(correct_count-sum_confidence)) /sum(count), or 0.0 if total count is zero. Bins need not have equal counts.8.Separate selection coverage from accepted error
Write
selective_error(labels, predictions, confidence, threshold). Equal-length lists contain class labels, predicted labels and confidences in[0,1]. Accept positions with confidence >= threshold. Return{"coverage": accepted/all, "risk": wrong/accepted}. Empty input has coverage 0.0; no accepted positions gives riskNone.9.Choose a feasible observed operating point
Write
choose_operating_point(points, max_fp). Each point is[threshold,tp,fp]with a finite threshold and nonnegative counts; thresholds are distinct. Among points with fp <=max_fp, choose the greatest tp, breaking ties by the higher threshold. Return its threshold, orNoneif no point qualifies. Do not invent an extra point.10.Merge group counts before macro averaging
Write
grouped_accuracy(records). Each record is[group,correct,total], with a string group and integers 0 <= correct <= total. Merge repeated groups first. Return {"micro": all correct/all total,"macro": mean merged-group accuracy excluding zero-total groups}. Either result is 0.0 when its denominator is empty.11.Apply fixed target-population weights
Write
standardized_accuracy(counts, weights). counts maps group names to[correct,total]; weights maps target groups to nonnegative weights. Return the weighted mean of observed group accuracies, normalized by total target weight. If any positive-weight group is absent or has total 0, returnNone. Zero total target weight also returnsNone. Ignore zero-weight groups.12.Preserve paired model correctness
Write
paired_outcomes(labels, a, b). Lists have equal length, true labels are non-Noneintegers or strings, and each prediction may also beNone. Treat a missing prediction as wrong. Return counts under keys both,a_only,b_onlyand neither, describing which models are correct on each same example. Include all keys for empty input.13.Align predictions by identifier and arrival
Write
align_predictions(labels, predictions). Each input contains[string_id,value]pairs. Label ids are unique; prediction ids may repeat, and the last prediction wins. Return{"matched": [id,label,prediction] rows, "missing": label ids with no prediction}, both in label order. Ignore prediction-only ids.Noneis a present value, not an absent record.14.Merge weighted loss numerators and masses
Write
merge_loss(parts), where each part is[loss_sum,weight_sum]with nonnegative finite values. A zero-weight part has zeroloss_sum. Return totalloss_sumdivided by totalweight_sum, orNoneif total weight is zero. Parts may represent different batch sizes; do not average their individual means.15.Aggregate selected token log probabilities
Write
masked_token_loss(logps, masks). Matching nested rows hold finite nonpositive true-token natural-log probabilities and Boolean selectors. Return {"sum": total selected negative log probability,"tokens": selected count,"mean": sum/tokens orNoneif none selected}. Rows may have different lengths. A selected log probability of 0 still counts.16.Count exact agreement on eligible sequences
Write
sequence_exact(truth, predicted, masks). Inputs have matching nested row shapes; labels are non-Nonevalues and predictions may beNone. A row is eligible only if its mask selects at least one position. It is correct only if all selected labels match. Return[correct_rows,eligible_rows], ignoring masked positions and all-masked rows.17.Deduplicate exact labeled span matches
Write
exact_spans(reference, predicted). Entries are[document_id,start,end]with a string id and integer start < end. Treat each list as a set of exact triples, removing duplicates. Return{"tp": intersection size, "fp": predicted-only size, "fn": reference-only size}. Overlap without identical document and boundaries is not a match.18.Measure common-prefix agreement on label paths
Write
hierarchy_score(reference, predicted). Equally long lists contain root-to-label paths of strings. A pair scores its common-prefix length divided by the longer path length. Two empty paths score 1.0; exactly one empty path scores 0.0. Return the mean pair score, or 0.0 for no pairs. Matching tokens after a mismatch earn no credit.19.Clip repeated token overlap counts
Write
token_overlap(reference, predicted)for lists of case-sensitive token strings. Let overlap be the sum, over tokens, of the smaller reference and predicted occurrence counts. Return 2*overlap/(len(reference)+len(predicted)). Two empty lists score 1.0; exactly one empty list scores 0.0. Token order does not affect this score.20.Summarize closed prediction intervals
Write
interval_summary(rows), where each row is[lower,upper,target]of finite numbers with lower <= upper. Coverage is the fraction with lower <= target <= upper; width ismean(upper-lower). Return{"coverage": ..., "width": ...}. Empty input returnsNonefor both fields. A zero-width interval can cover its exact target.21.Respect asymmetric quantile loss slopes
Write
quantile_loss(truth, predicted, q), with equally long finite numeric lists and 0 < q < 1. For error e = truth-predicted, loss is q*e when e >= 0 and (q-1)*e otherwise. Return mean loss or 0.0 for no examples. Implement this supplied unscaled formula, without converting it to absolute error.22.Select the worst supported group exactly
Write
worst_group(counts, minimum). counts maps string group names to[correct,total]with valid nonnegative integer counts, and minimum is positive. Consider only total >= minimum. Return the name with smallest correct/total, breaking exact ties alphabetically, orNoneif none qualify. Compare fractions exactly, without rounding rates.23.Apply supplied paired resample indices
Write
resample_deltas(a, b, draws). a and b are equally long finite per-example scores. Each draw is a list of valid indices, with repetitions allowed. For every draw return the mean ofb[i]-a[i]over its indices, orNonefor an empty draw. Preserve draw order and repeated selections; do not generate random draws.24.Use explicit nearest-rank percentile endpoints
Write
nearest_interval(values, low, high), with finite values and integer percentages 1 <= low <= high <= 100. Sort values and select each endpoint at one-based rank ceil(len(values)*percent/100), with no interpolation. Return[low_value,high_value], orNonefor empty input. Do not mutate values.25.Filter evaluation runs by version and label time
Write
eligible_runs(rows, dataset, model, as_of). Each dict has id, dataset, model, finished,label_at, status and score; times are integers, exceptlabel_atmay beNone. Return ids in input order only for matching dataset/model, status"done", both times <=as_of, and finite numeric score (booleans excluded). Missing label time or score makes a row ineligible.26.Count multilabel errors over the full label space
Write
multilabel_hamming(reference, predicted, classes). Inputs have equally many rows of valid class-index lists; classes is a positive integer. Deduplicate each row. Count symmetric-difference labels per pair and divide the total bynumber_of_rows*classes. Empty evaluation input returns 0.0. Empty label rows still contribute to that denominator.27.Apply directional mistake and rejection costs
Write
decision_cost(labels, predicted, costs, reject_costs). Labels are valid class indices and predictions are valid indices orNone.costs[true][predicted]andreject_costs[true]are nonnegative finite costs. Return mean realized cost, using the rejection cost forNone. Empty examples returnNone. Lists of labels and predictions have equal length.28.Keep separate observed support for each horizon
Write
horizon_errors(truth, predicted)for same-shaped rectangular numeric rows; either value at a position may beNone. For each column return[observed_count,mae], using only pairs where both values are present. No usable pairs gives[0,None]. Empty outer input returns []; zero-column rows also return []. Numeric zero is present data.29.Retain nondominated model measurements
Write
pareto_models(rows), with[unique_string_id,finite_score,nonnegative_latency]rows. Higher score and lower latency are preferred. A row is dominated if another has score >= its score and latency <= its latency, with at least one strict improvement. Return nondominated ids in original order. Identical measurements do not dominate each other.30.Report support and exact accuracy gate failures
Write
check_gates(reports, rules). reports maps names to valid[correct,total]counts. Rules are[name,min_count,num,den], with positivemin_count,den and 0<=num<=den. Return[name,reasons]for failing rules in order. Missing report:["missing"]. Otherwise add"support"if total<min_count, then"accuracy"if total>0 and correct*den<num*total. Empty reasons means pass.