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
print(contrastive_accuracy([[2.0, 1.0], [0.5, 3.0]]))
1.0
- Convert the input nested list into a matrix to represent the similarity scores between images and texts:
- 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: at index .
- Row 1: at index .
- The prediction vector is .
- Compare these predictions against the ground truth diagonal indices to count correct matches:
- Image 0 predicted text 0 (Correct).
- Image 1 predicted text 1 (Correct).
- Total correct predictions = .
- Calculate the accuracy by dividing the number of correct predictions by the total number of examples :
- 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.