FreeExam

Metric and Calibration Implementations

Thirty original Python problems on calibration fitting, corrected residual diagnostics, distribution scores, censored-outcome support, partition agreement and conformal calculations. Implement explicit numerical conventions without inferring unverified statistical guarantees.

These problems are original practice. They are not questions from a named employer or a live hiring loop.

  1. 1.Take a damped two-parameter calibration Newton step

    Write platt_step(rows,a,b,ridge,rate). Rows [finite_logit,0_or_1_label,weight>=0]. ridge>0, rate>=0. Calibrated probability=sigmoid(a*logit+b). Take ONE damped Newton step for weighted binary log loss plus ridge*(a*a+b*b)/2; BOTH parameters are penalized. Return new [a,b]. Gradient/Hessian definitions are in the starter docstring. Use stable sigmoid for large logits. No mutation.

  2. 2.Fit a temperature with stable candidate log loss

    Write choose_temperature(rows,candidates). Rows [nonempty_logit_list,gold_index], same width; finite moderate logits. Candidates positive finite temperatures. Score each by mean(logsumexp(logits/T)-gold_logit/T). Return [chosen_T,score]; within 1e-10 of the minimum ties toward smaller T. Use max subtraction. Empty rows or candidates return None. Do not generate candidates or mutate.

  3. 3.Apply a beta-style log-probability calibration map

    Write beta_map(values,a,b,c). Each p is strictly between 0 and 1; coefficients finite. Return sigmoid(a*ln(p)-b*ln(1-p)+c) per p, using log1p(-p) and a stable sigmoid. This applies supplied coefficients without fitting. a=b=1,c=0 is the identity map. Preserve value order and do not clip probabilities or mutate.

  4. 4.Normalize multiclass prior-shift weights

    Write shift_prior(rows,old_prior,new_prior). Matching nonempty vectors; rows are probability distributions, old_prior positive and sums to 1, new_prior nonnegative and sums to 1. For each row p, set w_j=p_j*new_prior_j/old_prior_j, then normalize w. Return None for a row whose total weight is zero. This implements the supplied reweighting, without validating label-shift assumptions. No mutation.

  5. 5.Merge calibration bins without dropping a small tail

    Write merge_calibration(bins,minimum). Ordered bins are [count,sum_probability,event_count], valid summaries; minimum>=1 integer. Accumulate adjacent bins left to right until count>=minimum, then emit. Merge a trailing incomplete group into the last emitted group, or emit alone if none. Return [source_bin_indices,count,sum_probability,event_count] groups. Keep zero-count bin indices. No mutation.

  6. 6.Retain negative pair-based calibration estimates

    Write residual_calibration(rows). Rows [string_bin,probability,0_or_1_label], probability in [0,1]. Residual r=label-probability. In each bin with n>=2 compute U=((sum(r))**2-sum(r*r))/(n*(n-1)). Return [sum(n*U)/used_rows,used_rows/all_rows], using only supported bins in the first denominator. If no supported bin, estimate None; empty total coverage 0. Do not clip negative U or mutate.

  7. 7.Exclude self-products from kernel calibration

    Write kernel_calibration(rows,bandwidth), bandwidth>0 finite. Rows [probability,0_or_1_label], probability in [0,1]. Residual r_i=label_i-p_i. Return sum over i!=j of r_i*r_j*exp(-(p_i-p_j)**2/(2*bandwidth**2))/(n*(n-1)). Fewer than two rows returns None. Keep negative results and repeated observations; do not include diagonal terms or mutate.

  8. 8.Decompose Brier loss using exact issued forecast values

    Write brier_parts(rows), [probability,0_or_1_label]. Group by EXACT forecast probability p, not wider bins. Let base=mean(label), rate_g=group mean label, n_g group count, N total. Return [mean((p-label)**2),base*(1-base),sum(n_g*(rate_g-base)**2)/N,sum(n_g*(p-rate_g)**2)/N]. Empty rows returns None. Entries are [Brier,uncertainty,resolution,reliability]. No mutation.

  9. 9.Normalize by the full probability-vector norm

    Write spherical_loss(rows). Rows [nonempty_probability_vector,gold_index] use nonnegative distributions summing to 1. Per row loss=1-p_gold/sqrt(sum(p_j*p_j)); return mean loss, or None for no rows. Use the full vector norm, no class-count division and no clipping. Smaller is better under this stated convention. No mutation.

  10. 10.Score weighted scalar ensembles including spread

    Write ensemble_crps(draws,observed). draws are [finite_value,nonnegative_weight], observed finite. Normalize weights by W. Return sum(w*abs(x-observed))/W - sum over i<j(w_i*w_j*abs(x_i-x_j))/W**2. Return None for W=0. Repeated atoms retain their supplied weight; zero weights add no mass. This is the supplied empirical CRPS loss. No mutation.

  11. 11.Score multivariate ensembles with Euclidean distances

    Write energy_loss(draws,observed). draws are [finite_vector,weight>=0], vectors match observed width, possibly zero. Normalize weights by W. Return weighted mean Euclidean distance to observed minus sum over i<j(w_i*w_j*Euclidean_distance(x_i,x_j))/W**2. W=0 returns None. Distances are NOT squared. Preserve duplicate atom mass and do not mutate.

  12. 12.Fit forecast scales on training history only

    Write scaled_forecast(train,truth,predicted,lag). Finite lists, matching truth/predicted lengths, lag>=1 integer. Training differences=train[i]-train[i-lag] for i>=lag. Return [mean(abs(errors))/mean(abs(training_differences)), sqrt(mean(errors**2)/mean(training_differences**2))]. Unsupported or zero scales yield None; no evaluation rows yields [None,None]. Never fit scales on truth. No mutation.

  13. 13.Normalize symmetric percentage error by observation weight

    Write weighted_smape(rows), finite [observed,predicted,weight>=0]. Per-row loss=2*abs(observed-predicted)/(abs(observed)+abs(predicted)); define loss=0 when both are zero. Return weighted mean loss, or None for total weight zero. Opposite signs can reach 2; do not divide by observed alone, add epsilon or use row count as the weighted denominator. No mutation.

  14. 14.Evaluate power deviance at zero outcomes

    Write power_deviance(rows,power), 1<power<2. Rows [y,mu] finite, y>=0,mu>0. Per row D=2*(y**(2-power)/((1-power)*(2-power))-y*mu**(1-power)/(1-power)+mu**(2-power)/(2-power)). Return mean D, or None for no rows. A zero y contributes zero to y**(2-power). Keep the power parameter and leading 2; no mutation.

  15. 15.Keep the mean and shape convention in count log loss

    Write count_logloss(rows,shape). Rows [nonnegative_integer_count,positive_finite_mean], shape>0 finite. Negative-binomial mass is Gamma(y+shape)/(Gamma(shape)*y!)*(shape/(shape+mean))**shape*(mean/(shape+mean))**y. Return mean negative NATURAL log mass, or None for empty rows. Use log-gamma/log1p, not factorial expansion or a Poisson approximation. No mutation.

  16. 16.Measure transport with actual category spacing

    Write ordered_transport(positions,left,right). Matching nonempty vectors; positions strictly increasing finite, left/right nonnegative distributions summing to 1. Return sum((positions[j+1]-positions[j])*abs(sum(left[:j+1])-sum(right[:j+1]))) for j=0..K-2. One category returns 0. Do not square CDF gaps, divide by category count or assume unit spacing. No mutation.

  17. 17.Use only earlier observed events in pair concordance

    Write event_concordance(rows), finite [time,event_bool,risk]. A pair is comparable only when times differ and its EARLIER row has event=True. Credit 1 if earlier risk is higher, 0.5 for equal risks, else 0. Return [mean_credit,comparable_pair_count], mean None if count=0. Exclude equal-time pairs even if one is an event. Repeated rows are distinct positions. No mutation.

  18. 18.Use censoring weights with the full cohort denominator

    Write censored_brier(rows,horizon,Gh). Rows [time,event_bool,S,Gleft], survival forecast S in [0,1], 0<Gh<=1. If time<=horizon and event, add S*S/Gleft (Gleft>0 there). If time>horizon add (1-S)**2/Gh. Otherwise add zero. Return [sum_contributions/N,contributing_row_count], or [None,0] when empty. Gleft is supplied censoring survival just BEFORE time, not an event probability. No mutation.

  19. 19.Use separate marginals in multiclass correlation

    Write multiclass_corr(rows,classes). classes>=1 integer; rows [gold_index,predicted_index] valid in 0..classes-1. N=row count, C=correct count, t_k=gold count, p_k=predicted count. Return (N*C-sum(t_k*p_k))/sqrt((N*N-sum(t_k*t_k))*(N*N-sum(p_k*p_k))). Zero denominator, including empty rows, returns None. Do not reduce to one-vs-rest averages or mutate.

  20. 20.Chance-correct weighted ordinal disagreement

    Write quadratic_kappa(rows,classes), classes>=1; valid integer [gold,predicted] class indices. Observed disagreement O=sum((gold-predicted)**2). Expected E=sum(gold_count[i]*pred_count[j]*(i-j)**2)/N over all ordered class pairs. Return 1-O/E, or None for N=0 or E=0. Preserve declared ordinal indices; do not relabel observed classes densely or use uniform marginals. No mutation.

  21. 21.Compare partitions by chance-corrected observation pairs

    Write adjusted_pairs(rows), paired string partition labels. Let J=sum choose(cell_count,2), A=sum choose(left_count,2), B=sum choose(right_count,2), T=choose(N,2). Return (J-A*B/T)/((A+B)/2-A*B/T). Return 1 for N<2 or a zero denominator (degenerate equivalent partitions). Label spelling/bijections are irrelevant. Repeated rows are distinct observations. No mutation.

  22. 22.Separate homogeneity and completeness before combining them

    Write partition_information(rows), paired string partition labels. Let HL,HR be natural-log marginal entropies, I mutual information from empirical joint counts. Homogeneity=I/HL, or 1 if HL=0; completeness=I/HR, or 1 if HR=0. Return [homogeneity,completeness,2*h*c/(h+c)], final value 0 if h+c=0. Empty rows return None. No label matching or mutation.

  23. 23.Penalize location and scale disagreement

    Write concordance_corr(rows), finite [reference,predicted] pairs. Use population means mx,my, variances vx,vy and covariance cov over all pairs. Return 2*cov/(vx+vy+(mx-my)**2). Empty input returns None. If denominator is zero, both coordinates are the same constant: return 1. Unlike Pearson, a location shift or scale difference reduces agreement. No mutation.

  24. 24.Double-center distances before correlation normalization

    Write distance_corr(rows), <=40 finite scalar [x,y] pairs. Build absolute-distance matrices a,b. Double-center each: Aij=aij-rowmean_i-colmean_j+grandmean, similarly B. Let C=mean(A*B), Vx=mean(A*A), Vy=mean(B*B) over ALL n*n entries. Return sqrt(max(0,C/sqrt(Vx*Vy))); zero variance returns 0, empty rows None. Use biased centering including diagonals. No mutation.

  25. 25.Apply the threshold odds penalty to false-positive decisions

    Write net_benefit(rows,thresholds). Rows [probability,0_or_1_label], probability in [0,1]; thresholds in [0,1). At threshold t accept every p>=t. Return (true_positives-false_positives*t/(1-t))/N per threshold, preserving order; empty rows produce None per threshold. Rejected positives add no direct term. This implements a supplied utility rule, not a decision recommendation. No mutation.

  26. 26.Keep an infinite cutoff for an unsupported conformal rank

    Write residual_intervals(calibration,predictions,alpha), 0<alpha<1. Finite calibration rows [observed,predicted]. Sort absolute residuals; rank=ceil((n+1)*(1-alpha)), exact decimals. If rank<=n use that one-based residual q; else q=None means infinite. Return [rank,q,[[p-q,p+q] per prediction]], use [None,None] for infinite intervals. Never clip rank or infer coverage assumptions. No mutation.

  27. 27.Use supplied randomization within target probability mass

    Write adaptive_scores(rows). Each row [probability_vector,gold_index,u] has a nonempty distribution and supplied u in [0,1]. Sort classes by decreasing probability, ties by class index. Score=sum(probabilities preceding gold)+u*probability_of_gold. Return scores in row order. Include preceding tied classes; do not resample u, use gold rank alone or claim coverage from this kernel. No mutation.

  28. 28.Balance probabilities with bounded intercept search

    Write balance_intercept(rows,lower,upper,steps). Nonempty finite [logit,0_or_1_label] rows have a finite balancing root in supplied lower<=upper; steps integer 0..60. At midpoint b compare sum(sigmoid(logit+b)) with sum(labels): if equal return b, if less set lower=b, otherwise set upper=b. After steps return the final bracket midpoint. Empty rows returns None. Use stable sigmoid; no mutation.

  29. 29.Score full covariance and log determinant

    Write moment_loss(observed,mean,covariance). Matching finite vectors of width 1..4; supplied covariance symmetric positive definite. Return ln(det(covariance))+(observed-mean)^T*inverse(covariance)*(observed-mean). Use the full covariance, not diagonal-only variances. This is a smaller-is-better moment score with NO added Gaussian normalization constant; negative values are valid. No mutation.

  30. 30.Combine median and alpha-weighted interval losses

    Write interval_aggregate(observed,median,intervals). Finite values; intervals are [alpha,lower,upper], 0<alpha<1, lower<=upper. IS=(upper-lower)+2/alpha*max(lower-observed,observed-upper,0). Return (0.5*abs(observed-median)+sum(alpha/2*IS))/(K+0.5), K=interval count. With no intervals this is absolute median error. Keep endpoint equality inside; do not average intervals equally or mutate.