868. Fix accuracy computed with the wrong argmax axis
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.
def 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,).