collate_fn para Entradas de Tamanho Variável
Preencha e empilhe amostras irregulares
collate_fn para Entradas de Tamanho Variável é uma aula grátis de Deep Learning Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Deep Learning Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Deep Learning Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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, labelsMask 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. 🎉
Perguntas Frequentes
A aula “collate_fn para Entradas de Tamanho Variável” é grátis?
Sim — o texto completo de “collate_fn para Entradas de Tamanho Variável” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Deep Learning Academy, atualize para CoddyKit PRO. O curso de Deep Learning Academy inclui 4 aulas no total.
O que vou aprender em “collate_fn para Entradas de Tamanho Variável”?
Preencha e empilhe amostras irregulares Você pratica Deep Learning Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Deep Learning Academy?
Nenhuma experiência prévia é necessária. Deep Learning Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “collate_fn para Entradas de Tamanho Variável”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Deep Learning Academy?
Sim. Cada aula de Deep Learning Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Escreva uma Classe de Conjunto de Dados Personalizada
- Lotes, Embaralhamento e num_workers
- collate_fn para Entradas de Tamanho Variável
- Normalize e Padronize as Entradas