PIXELBANKv9.1.0
Menu

Prompt-Ensemble Zero-Shot Classifier Weights

Problem Statement

CLIP's zero-shot accuracy jumps when each class is described by many prompt templates whose embeddings are averaged into a single classifier weight. Build those per-class weights from the template embeddings.

Background

For class c with template embeddings e_{c,1}, ..., e_{c,T} (each already L2-normalized), the ensembled classifier weight is the mean of the normalized templates, then re-normalized:

wc=eˉc∥eˉc∥2,eˉc=1T∑tec,tw_c = \frac{\bar{e}_c}{\lVert \bar{e}_c \rVert_2}, \qquad \bar{e}_c = \frac{1}{T}\sum_{t} e_{c,t}

This is exactly what OpenAI's zero-shot code does with its 80 ImageNet templates. The re-normalization matters: averaging unit vectors gives a shorter vector, and the final classifier must sit back on the unit sphere so logits stay comparable across classes.

Your Task

Implement:

def ensemble_weights(class_templates):
  • class_templates: list over classes; each element is a list of template embeddings (each a list of floats).

Return the (num_classes, D) weight matrix as a nested list rounded to 4 decimals.

Input Format

  • class_templates: num_classes lists, each of T_c embeddings of dimension D.

Output Format

  • A (num_classes, D) nested list rounded to 4 decimals.

Sample

ct = [[[1.0, 0.0], [0.0, 1.0]]]
print(ensemble_weights(ct))

Output:

[[0.7071, 0.7071]]

Example:

Input:
ct = [[[1.0, 0.0], [0.0, 1.0]]]
print(ensemble_weights(ct))
Output:
[[0.7071, 0.7071]]
Reasoning:
  • Compute the mean embedding: For the single class, average the two template vectors [1.0,0.0][1.0, 0.0] and [0.0,1.0][0.0, 1.0] component-wise to get eˉ=[1.0+0.02,0.0+1.02]=[0.5,0.5]\bar{e} = \left[\frac{1.0+0.0}{2}, \frac{0.0+1.0}{2}\right] = [0.5, 0.5].
  • Calculate the L2 norm: Determine the magnitude of the mean vector to prepare for re-normalization: ∥eˉ∥2=0.52+0.52=0.25+0.25=0.5≈0.7071\lVert \bar{e} \rVert_2 = \sqrt{0.5^2 + 0.5^2} = \sqrt{0.25 + 0.25} = \sqrt{0.5} \approx 0.7071.
  • Re-normalize the vector: Divide the mean vector by its norm to project it back onto the unit sphere, ensuring the classifier weight has a magnitude of 1: w=[0.5,0.5]0.7071≈[0.7071,0.7071]w = \frac{[0.5, 0.5]}{0.7071} \approx [0.7071, 0.7071].
  • Round to 4 decimals: Apply the required precision formatting to the resulting weights, yielding [0.7071,0.7071][0.7071, 0.7071].
  • The final output is [[0.7071, 0.7071]]

Constraints:

  • 1 <= num_classes <= 1000, 1 <= T_c, 1 <= D <= 1024.
  • Average the templates per class, then L2-normalize (guard a zero mean by leaving it zero).
  • Round every entry to 4 decimals; avoid -0.0.
🔒

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.
Prompt-Ensemble Zero-Shot Classifier Weights - Medium | PixelBank