Model Evaluation Implementations
Original Python applied AI interviews on probability scores, calibration support, tied ranking groups, selective risk, structured predictions, and comparable evaluation evidence.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Align required predictions and expose duplicate evidence
Write
align_predictions(required, rows). required lists unique ids; rows are[id,label_or_None]. Return {"aligned":[id,only_label_or_None]in required order,"missing":required ids with no row,"duplicates":sorted ids with >1 row anywhere,"extra":sorted ids outside required}. Repeated identical rows are duplicates; ambiguous ids align toNone. Keep missing order; do not mutate.2.Score all class coordinates with an unscaled quadratic loss
Write
quadratic_scores(rows, classes). classes lists unique nonempty class names; each row[gold,prob_dict]has gold in classes and probabilities for every class summing to 1. Per row compute sum over classes of (p[class]-int(class==gold))**2, without dividing by class count or 2. Return{"per_item":scores,"mean":mean or None for no rows}. Do not mutate.3.Distinguish unsupported observed events from harmless zeros
Write
event_logloss(rows, floor). Rows[gold,prob_dict]contain valid distributions with gold present; 0<=floor<=1. Each loss is -ln(max(prob_dict[gold],floor)), orNoneif that maximum is zero. Return {"per_item":losses,"mean":mean only when rows exist and every loss is defined, otherwiseNone}. Zero probability of another class is harmless. Do not mutate.4.Weight log loss by supported soft-target mass
Write
soft_cross_entropy(target, predicted). Equal-length nonempty lists are probability distributions in matching class order. Return -sum(target[i]*ln(predicted[i])) over positive target entries. ReturnNoneif any positive target entry has predicted probability zero, or if the lists are empty. Zero target entries contribute zero even when prediction is zero. No clipping or mutation.5.Give fractional top-k credit at a tied score boundary
Write
tied_topk(scores, gold, k). scores maps class names to finite scores; gold is present; k>=0. Let g count classes strictly above the gold score and t count classes tied with gold, including gold. Return min(1,max(0,(k-g)/t)), its inclusion probability under uniform tie-breaking for k slots. k may exceed class count. Do not depend on class insertion order or mutate.6.Normalize entropy over declared predictive class support
Write
normalized_entropy(probabilities). A nonempty list is a nonnegative distribution summing to 1. Return -sum(p*ln(p)for p>0)/ln(K), where K is list length. Return 0 for K=1, andNonefor an empty list. Keep zero-probability classes in K; do not renormalize to observed positive classes or mutate.7.Weight frozen-bin calibration gaps by example support
Write
calibration_error(rows, edges). Rows[confidence,correct_bool], confidence in[0,1]; edges strictly increase from 0 to 1. Bins are [left,right), except the last includes 1; internal boundaries go right. Return sum over bins of abs(sum(correct)-sum(confidence))/N, orNoneif N=0. Empty bins contribute zero. Do not average bin gaps equally or mutate.8.Retain probability and event support for every uniform bin
Write
reliability_table(rows, bins). Rows[probability,event_bool], probability in[0,1]; bins>=1. Assign index min(floor(probability*bins),bins-1). Return[index,count,event_count,probability_sum]for every bin in index order, including empty bins. Keep p=0 and p=1; interpret decimals exactly and sum actual probabilities. Do not mutate.9.Compare all positive-negative pairs with half-credit ties
Write
pair_auc(rows). Rows[finite_score,positive_bool]. For every positive-negative pair, give 1 if positive score is greater, 0.5 if equal, else 0. Return mean pair credit, orNoneunless both classes occur. Repeated rows are separate observations. Do not threshold scores, pair by row position or mutate.10.Advance average precision by whole tied-score groups
Write
grouped_ap(rows). Rows[finite_score,positive_bool]. Process distinct scores descending, admitting all tied rows together. At each group add (new_positives/total_positives)*(cumulative_positives/cumulative_rows). Return this sum, orNonewhen no positive exists. Do not break ties by input order or use trapezoidal interpolation. No mutation.11.Integrate a ROC polyline to a stated false-positive cap
Write
partial_roc(points, cap). points lists[false_positive_rate,true_positive_rate]in nondecreasing coordinate order, starting[0,0]and ending[1,1]; vertical segments are allowed. 0<=cap<=1. Return unstandardized area under its piecewise-linear path from x=0 to cap. Interpolate a segment crossed by cap; vertical segments have zero area. Do not mutate.12.Advance threshold confusion counts by complete score groups
Write
threshold_trace(rows). Rows[finite_score,positive_bool]. For each distinct score t descending, classify score>=t as positive. Return[t,tp,fp,fn,tn]after admitting the whole tied group. Include every threshold once; repeated rows count separately. Empty input returns []. Do not use strict score>t, split ties or mutate.13.Choose actions by aligned exact-decimal expected loss
Write
choose_action(probabilities, losses). probabilities maps classes to a valid distribution; losses maps action names to complete class->finite_costdictionaries. Interpret decimals exactly. Per action computesum(p[class]*cost[class]). Return {"action":lowest-cost action, ties alphabetically, orNoneif no actions,"costs":[action,cost]sorted by action}. Costs may be negative. No mutation.14.Keep accepted risk distinct from abstention and coverage
Write
selective_report(rows). Rows[accepted_bool,correct_bool]; correctness of rejected rows is ignored. Return {"total":N,"accepted":A,"errors":accepted incorrect count,"coverage":A/N orNoneif N=0,"risk":errors/A orNoneif A=0}. Rejection is neither a correct answer nor an accepted error. Count every row without mutation.15.Choose maximum empirical coverage without splitting ties
Write
coverage_threshold(rows, limit). Rows[confidence,correct_bool]; confidences in[0,1], 0<=limit<=1, exact decimals. Try each observed confidence t, accepting all confidence>=t. Choose the feasible t with largest accepted count where errors/count<=limit. Return{"threshold":t,"accepted":count,"errors":errors}; if none, returnNone,0,0 in those fields. Check all groups. No mutation.16.Integrate selective risk after whole confidence groups
Write
risk_coverage_area(rows). Rows[finite_confidence,correct_bool]. Process distinct confidences descending, adding each whole tied group. After a group let e be cumulative errors and a cumulative accepted count; add (group_size/N)*(e/a). Return the sum, orNonefor N=0. This is a right-endpoint step area; do not split ties or interpolate. No mutation.17.Bound correctness over admissible gold-label sets
Write
correctness_bounds(rows). Rows[predicted_label,nonempty_possible_gold_labels]. For each row lower correctness is 1 iff the distinct gold set is exactly{prediction}; upper is 1 iff it contains prediction. Return{"lower":mean lower,"upper":mean upper}, bothNonefor no rows. Repeated labels do not add uncertainty or weight. Deterministic bounds, not confidence intervals. No mutation.18.Average recalls over supported gold classes
Write
balanced_report(rows). Rows[gold,prediction]contain string labels. For each observed gold class return[label,gold_count,correct/gold_count], sorted by label. Return {"recalls":these rows,"balanced":their mean recall orNoneif empty,"prediction_only":sorted predicted labels absent from all golds}. Prediction-only classes are reported, not added as zero-recall classes. No mutation.19.Adjust agreement using both observed label marginals
Write
agreement_kappa(rows). Rows[left_label,right_label]are paired string labels. Let n=len(rows), d=number equal, and m=sum(left_count[label]*right_count[label])over all seen labels. Return (n*d-m)/(n*n-m), orNonefor n=0 or zero denominator. Use separate left/right marginals; do not replace chance agreement by a uniform-class rate or mutate.20.Compute binary correlation only with nondegenerate margins
Write
binary_mcc(rows). Rows[gold_bool,predicted_bool]. Count TP,FP,FN,TN and return (TP*TN-FP*FN)/sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN)). ReturnNoneif the product under the root is zero, including empty input. Booleans define positive orientation. Do not substitute accuracy for correlation or mutate.21.Separate exact label-set equality from coordinate error
Write
multilabel_report(rows, classes). classes is a unique label universe, possibly empty; rows are[gold_labels,predicted_labels]containing only declared labels. Ignore repeated labels. Return {"exact":fraction of rows with equal sets orNoneif no rows,"hamming":total symmetric-difference size/(row_count*class_count), orNoneif that denominator is zero}. Do not infer classes or mutate.22.Score ordered probabilities across cumulative boundaries
Write
ordinal_score(probabilities, gold). probabilities is a nonempty distribution over ordered categories, gold its 0-based category index. For each boundary j=0..K-2, square (sum(probabilities[:j+1])-int(gold<=j)); return their sum/(K-1). Return 0 for K=1. Preserve category order; do not score individual coordinates or include the final certain boundary. No mutation.23.Charge interval width and explicit outside penalties
Write
interval_scores(rows, alpha). Rows[lower,upper,observed]are finite numbers with lower<=upper; 0<alpha<1. Per row score (upper-lower)+(2/alpha)*max(lower-observed,observed-upper,0). Return{"per_item":scores,"mean":mean or None if no rows}. Endpoints incur no outside penalty. Compute this supplied loss without claiming interval coverage. Do not mutate.24.Keep quantile residual orientation and scale explicit
Write
pinball_scores(rows, quantile). Rows[observed,predicted]are finite; 0<=quantile<=1. Residual r=observed-predicted; loss is quantile*r if r>=0, else (quantile-1)*r. Return{"per_item":losses,"mean":mean or None if empty}. Use this unscaled loss: quantile=0.5 gives half the absolute error. Do not reverse residuals or mutate.25.Retain observed target support separately for each horizon
Write
horizon_mae(rows, horizons). horizons>=0; rows[horizon,target_or_None,prediction]have 0<=horizon<horizons and finite numeric predictions/observed targets. Ignore rows whose target isNone. Return[horizon,observed_count,mean_absolute_error_or_None]for every horizon 0..horizons-1. Zero targets are observed; keep repeated observations and unsupported horizons. Do not mutate.26.Match spans one-to-one instead of reusing gold evidence
Write
span_report(predicted, gold, threshold). Spans[label,start,end]have integer start<end, half-open. An edge requires equal labels and intersection/union length>=threshold, an exact decimal in (0,1]. Return {"matches":maximum one-to-one match count,"precision":matches/len(predicted)orNone,"recall":matches/len(gold)orNone}. Duplicate spans are separate vertices. Do not mutate.27.Separate unsupported rubric evidence from scored failures
Write
rubric_report(rows, required). rows lists criterion->True/False/Nonedictionaries; required lists unique names. If any required key is absent/Nonethe row is unsupported, even if another isFalse. Otherwise it passes iff all required values areTrue; other rows fail. Return{"passed":P,"failed":F,"unsupported":U,"rate":P/(P+F) or None}. Ignore optional; empty required passes. No mutation.28.Compare models only on shared answered gold identities
Write
common_support(gold, a, b). gold maps ids to labels; a,b map ids to labels orNonefor abstention. Use gold ids present with non-Nonepredictions in both models; extra predictions are ignored. Return {"ids":sorted compared ids,"a":A accuracy orNoneif none,"b":B accuracy orNone,"excluded":sorted unscored gold ids}. Empty-string labels are observed. Do not mutate.29.Align weighted probabilities by declared class identity
Write
ensemble_probabilities(weights, sources, classes). weights maps models to finite weights>=0; sources maps models to class->probability dicts; classes are unique ordered names. Return[class,weighted_mean]using exact decimals and total model weight. Missing positive-weight models or required classes returnNone. Ignore zero-weight models/extra classes; zero total returnsNone. No mutation.30.Fit a calibration map once and freeze it for queries
Write
calibration_map(rows, values, bins, alpha). rows[probability,event_bool]are calibration data; values are query probabilities, all in[0,1]; bins>=1, alpha>0, exact decimals. Bin index=min(floor(p*bins),bins-1). Fit rate=(events+alpha)/(count+2*alpha) per bin. Return{"rates":all bin rates,"mapped":query bin rates in query order}. Queries never affect fitting. Do not mutate.