BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Evaluation metrics28 of 33 in topic

809. Calibrate a classifier with temperature scaling

MediumEvaluation metrics Pro

Why it matters Calibrated confidence decides when an LLM classifier or router should abstain or escalate to a human.

Modern networks are often overconfident: they say 99% when they are right 80% of the time. Temperature scaling divides the logits by one number T > 0 chosen on a validation set. It changes confidence without changing any argmax prediction.

Write fit_temperature(logits, labels, temps). logits is (n, C), labels a length-n list of class ids, temps a list of candidate T values. For each T compute the mean negative log likelihood of softmax(logits / T) at the true labels (use a stable log-softmax). Return (best_T, best_nll) for the T with the lowest NLL (ties: the first in temps).

Functiondef fit_temperature(logits, labels, temps)

Example 1

Input: fit_temperature([[2.0, 0.0], [0.0, 2.0]], [0, 1], [1.0, 2.0])

Output: (1.0, 0.1269)

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

Loop over candidate temperatures and score each one.

Hint 2

Use log-softmax with the row max subtracted so logits like 1000 do not overflow.

Hint 3

Keep the first T when two give the same NLL.

Common mistakes
  • Multiplying by T instead of dividing.
  • Computing softmax then log, which overflows or gives log(0) on large logits.
Understand the idea

Dividing logits by T > 1 flattens the softmax and lowers confidence; T < 1 sharpens it. The argmax never changes, so accuracy is untouched. The T with the lowest validation NLL is the best calibrated in the likelihood sense.

Worked example

logits [2, 0] with true class 0 at T = 1: NLL = log(1 + e^-2) = 0.127.

NLL(T) = mean(-log_softmax(z / T)[y]); pick the minimum
Topics
Evaluation metrics
Similar questions
  • Compute ROC AUC by counting ranked pairsMedium
  • Grade a search ranking with NDCG at kMedium
  • Compute macro and micro F1 for a multi-class classifierMedium
  • Measure rater agreement with Cohen's kappaMedium
All Evaluation metrics problems
Report
809 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def fit_temperature(logits, labels, temps):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS