0Pricing
Deep Learning Academy · Lección

collate_fn para entradas de longitud variable

Rellene y apile muestras irregulares

collate_fn para entradas de longitud variable es una lección gratuita de Deep Learning Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Deep Learning Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Deep Learning Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

When Samples Don't Match

Stacking into a batch needs every sample the same shape. But sentences and audio clips have different lengths, so the default collate step fails. 🧩

What collate_fn Does

The DataLoader gathers a list of samples and passes them to collate_fn, which merges them into one batch. By default it simply stacks tensors.

Ragged Inputs Break Stacking

Try to stack a length-5 and a length-8 sequence and PyTorch raises a shape error. Ragged lengths are exactly the case a custom collate must handle.

Write Your Own collate_fn

You pass a function to the DataLoader's collate_fn argument. It receives a list of samples and returns whatever batch shape your model expects.

loader = DataLoader(ds, batch_size=4, collate_fn=my_collate)

Step One: Split the List

Inside your function, unzip the list of pairs into separate sequences and labels. Now you can treat each group on its own before merging.

def my_collate(batch):
    seqs, labels = zip(*batch)

Pad to the Longest

The trick for variable lengths is padding: extend every sequence to the longest one with a filler value, so they finally share a shape.

pad_sequence Does It for You

PyTorch ships pad_sequence, which pads a list of tensors to equal length and stacks them. Set batch_first so the batch dimension comes first.

from torch.nn.utils.rnn import pad_sequence
padded = pad_sequence(seqs, batch_first=True)

Remember the Real Lengths

Padding adds fake tokens, so also return each sequence's true length. Your model uses these to ignore the padded positions during the forward pass.

lengths = torch.tensor([len(s) for s in seqs])

Stack the Labels

Labels are usually fixed size, so a normal stack works for them. Return the padded inputs, the lengths, and the stacked labels together.

labels = torch.stack(labels)
return padded, lengths, labels

Mask Out the Padding

Later you build a mask from the lengths so the loss and attention skip padded slots. Padding fills shape without polluting the gradients.

One Function, Any Shape

With a custom collate_fn, the same DataLoader handles text, audio, and graphs. You control exactly how loose samples become one tidy batch.

Quick Check

Why do variable-length sequences need a custom collate_fn?

Recap

A custom collate_fn turns a list of uneven samples into one batch, usually by padding sequences to equal length and tracking their real sizes. 🎉

Preguntas frecuentes

¿La lección «collate_fn para entradas de longitud variable» es gratis?

Sí — el texto completo de «collate_fn para entradas de longitud variable» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Deep Learning Academy, actualiza a CoddyKit PRO. El curso de Deep Learning Academy incluye 4 lecciones en total.

¿Qué aprenderé en «collate_fn para entradas de longitud variable»?

Rellene y apile muestras irregulares Practicas Deep Learning Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Deep Learning Academy?

No se requiere experiencia previa. Deep Learning Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «collate_fn para entradas de longitud variable»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Deep Learning Academy?

Sí. Cada lección de Deep Learning Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Escriba una clase Dataset personalizada
  2. Agrupación en lotes, barajado y num_workers
  3. collate_fn para entradas de longitud variable
  4. Normalice y estandarice las entradas
← Volver a Deep Learning Academy