Embeddings para IA
4.11.4kata 4 de 4

Zero-Shot Classification

Clasificar sin ejemplos etiquetados

La clasificación zero-shot usa embeddings para etiquetar textos sin ejemplos de entrenamiento. La idea: embebe el texto a clasificar, embebe las etiquetas candidatas como frases descriptivas ('this text is about sports'), y elige la etiqueta cuyo embedding sea más cercano al texto.

La formulación de las etiquetas es crítica. Las palabras sueltas ('sports', 'tech') son ambiguas y tienen embeddings pobres. Las frases descriptivas ('this text is about sports') anclan mejor la semántica. Incluso mejor: 'this is a news article about professional sports and athletic competitions' es más explícito.

Zero-shot es increíblemente práctico porque requiere CERO datos etiquetados. Es el primer paso para cualquier tarea de clasificación nueva: prueba zero-shot, mide accuracy, y solo si es mala, considera recolectar datos y hacer fine-tuning.

structure.txt
import numpy as np

labels = [
    'this text is about sports and athletic competitions',
    'this text is about technology and software engineering',
    'this text is about politics and government',
    'this text is about cooking and recipes',
]

# Embed labels once
label_vecs = embed_model.encode(labels)
label_vecs_norm = label_vecs / np.linalg.norm(label_vecs, axis=1, keepdims=True)

def classify_zero_shot(text: str) -> dict:
    text_vec = embed_model.encode(text)
    text_vec_norm = text_vec / np.linalg.norm(text_vec)

    # Cosine similarity with each label
    scores = label_vecs_norm @ text_vec_norm

    # Return top-3 with scores
    top_idx = np.argsort(scores)[::-1][:3]
    return [
        {'label': labels[i].split('about ')[-1], 'score': float(scores[i])}
        for i in top_idx
    ]

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    labels = ['sports', 'tech', 'politics', 'cooking'] label_vecs = embed(labels) score = label_vecs @ text_vec # text_vec not normalized

  2. 02

    # Return only the top label without alternatives top_label = labels[np.argmax(scores)]

  3. 03

    labels = ['news about sports', 'news about tech', 'news about politics'] # What if text is about cooking?