PIXELBANKv9.1.0
Menu

Contrastive Accuracy at the Diagonal

Problem Statement

In a CLIP batch of N paired image-text examples, the correct match for image i is text i β€” the diagonal of the similarity matrix. Measure the image-to-text retrieval accuracy: the fraction of rows whose argmax lands on the diagonal.

Background

Given the N x N logits matrix S (row = image, column = text), the image-to-text prediction for row i is argmax_j S[i][j]. It is correct iff that argmax equals i. Break ties by the smallest column index (numpy's argmax default). Accuracy is the count of correct rows divided by N.

Your Task

Implement:

def contrastive_accuracy(logits):

Return the image-to-text accuracy as a float rounded to 4 decimals.

Input Format

  • logits: N x N nested list.

Output Format

  • A float rounded to 4 decimals.

Sample

print(contrastive_accuracy([[2.0, 1.0], [0.5, 3.0]]))

Output:

1.0

Example:

Input:
print(contrastive_accuracy([[2.0, 1.0], [0.5, 3.0]]))
Output:
1.0
Reasoning:
  • Convert the input nested list into a 2Γ—22 \times 2 matrix SS to represent the similarity scores between images and texts: S=[2.01.00.53.0]S = \begin{bmatrix} 2.0 & 1.0 \\ 0.5 & 3.0 \end{bmatrix}
  • Determine the predicted text index for each image by finding the column index of the maximum value in each row (resolving ties by the smallest index, though none exist here):
    • Row 0: max⁑(2.0,1.0)=2.0\max(2.0, 1.0) = 2.0 at index 00.
    • Row 1: max⁑(0.5,3.0)=3.0\max(0.5, 3.0) = 3.0 at index 11.
    • The prediction vector is [0,1][0, 1].
  • Compare these predictions against the ground truth diagonal indices [0,1][0, 1] to count correct matches:
    • Image 0 predicted text 0 (Correct).
    • Image 1 predicted text 1 (Correct).
    • Total correct predictions = 22.
  • Calculate the accuracy by dividing the number of correct predictions by the total number of examples N=2N=2: Accuracy=22=1.0\text{Accuracy} = \frac{2}{2} = 1.0
  • The final output is 1.0

Constraints:

  • 1 <= N <= 1000; the matrix is square.
  • Ties in a row go to the smallest column index.
  • Accuracy = correct_rows / N, rounded to 4 decimals.
πŸ”’

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Contrastive Accuracy at the Diagonal - Easy | PixelBank