BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Debug and fix13 of 16 in topic

868. Fix accuracy computed with the wrong argmax axis

EasyDebug and fix

Why it matters Eval bugs make you ship the wrong model. An argmax over the batch axis still returns numbers, and broadcasting hides the mistake.

The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.

accuracy(probs, labels) should return the fraction of rows whose highest-probability class equals the label. Ties pick the lowest class index (np.argmax behaviour).

Inputs: probs is a list or ndarray of shape (n, k). labels is a list or ndarray of n ints.

Return a Python float rounded to 4 decimals.

Functiondef accuracy(probs, labels)

Example 1

Input: accuracy([[0.9, 0.1], [0.2, 0.8], [0.6, 0.4]], [0, 1, 1])

Output: 0.6667

Example 2

Input: probs = [[0.1, 0.7, 0.2], [0.3, 0.3, 0.4]], labels = [1, 2]

Output: 1.0

Example 3

Input: probs = [[0.2, 0.8], [0.7, 0.3]], labels = [0, 1]

Output: 0.0

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 6 tests to be accepted.
Hint 1

What shape does argmax(axis=0) return?

Hint 2

Predictions are per row.

Hint 3

Use axis=1.

Common mistakes
  • Comparing probabilities to labels directly.
  • Using axis=-1 on 1D input.
  • Not rounding.
Understand the idea

probs has one row per example. The prediction for each example is the argmax across its classes, which is axis 1. Axis 0 gives, for each class, which example is most confident, a completely different array that only has the right length when n equals k.

Shapes and data flow
probs: (n, k). pred: (n,).
Topics
Debug and fix
Similar questions
  • Fix the softmax that returns nanEasy
  • Fix the LayerNorm that normalises the wrong axisEasy
  • Fix the cross-entropy that returns infEasy
  • Fix the F1 score that crashes on empty predictionsEasy
All Debug and fix problems
Report
868 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
import numpy as np
​
def accuracy(probs, labels):
p = np.asarray(probs, dtype=float)
pred = p.argmax(axis=0)
return round(float((pred == np.asarray(labels)).mean()), 4)
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 6 tests.

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