FreeExam

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. 1.Count weighted outcomes and missing predictions

    Write weighted_outcomes(labels, predictions, weights). Labels are 0/1; predictions are 0/1 or None. Lists have equal length and weights are nonnegative. Return a dict with tp, fp, fn, tn and missing weighted totals. A None prediction contributes only to missing, regardless of its label. Include every key even for empty input.

  2. 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. 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, or None if either class is absent. Do not threshold scores.

  4. 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. 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. 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. 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. 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 risk None.

  9. 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, or None if no point qualifies. Do not invent an extra point.

  10. 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. 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, return None. Zero total target weight also returns None. Ignore zero-weight groups.

  12. 12.Preserve paired model correctness

    Write paired_outcomes(labels, a, b). Lists have equal length, true labels are non-None integers or strings, and each prediction may also be None. Treat a missing prediction as wrong. Return counts under keys both, a_only, b_only and neither, describing which models are correct on each same example. Include all keys for empty input.

  13. 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. None is a present value, not an absent record.

  14. 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 zero loss_sum. Return total loss_sum divided by total weight_sum, or None if total weight is zero. Parts may represent different batch sizes; do not average their individual means.

  15. 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 or None if none selected}. Rows may have different lengths. A selected log probability of 0 still counts.

  16. 16.Count exact agreement on eligible sequences

    Write sequence_exact(truth, predicted, masks). Inputs have matching nested row shapes; labels are non-None values and predictions may be None. 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. 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. 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. 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. 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 is mean(upper-lower). Return {"coverage": ..., "width": ...}. Empty input returns None for both fields. A zero-width interval can cover its exact target.

  21. 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. 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, or None if none qualify. Compare fractions exactly, without rounding rates.

  23. 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 of b[i]-a[i] over its indices, or None for an empty draw. Preserve draw order and repeated selections; do not generate random draws.

  24. 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], or None for empty input. Do not mutate values.

  25. 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, except label_at may be None. 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. 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 by number_of_rows*classes. Empty evaluation input returns 0.0. Empty label rows still contribute to that denominator.

  27. 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 or None. costs[true][predicted] and reject_costs[true] are nonnegative finite costs. Return mean realized cost, using the rejection cost for None. Empty examples return None. Lists of labels and predictions have equal length.

  28. 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 be None. 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. 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. 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 positive min_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.