可変長入力のためのcollate_fn
長さの異なるサンプルをパディングして積み重ねます
「可変長入力のためのcollate_fn」はCoddyKit上の無料Deep Learning Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはDeep Learning Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Deep Learning Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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. 🎉
よくある質問
「可変長入力のためのcollate_fn」レッスンは無料ですか?
はい。「可変長入力のためのcollate_fn」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Deep Learning Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Deep Learning Academyコースには全4レッスンが含まれています。
「可変長入力のためのcollate_fn」で何を学びますか?
長さの異なるサンプルをパディングして積み重ねます ブラウザで直接実行するハンズオンコードでDeep Learning Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Deep Learning Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのDeep Learning Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「可変長入力のためのcollate_fn」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このDeep Learning Academyレッスンでコードを書いて実行できますか?
はい。すべてのDeep Learning Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- カスタムDatasetクラスを書く
- バッチ化、シャッフル、num_workers
- 可変長入力のためのcollate_fn
- 入力を正規化・標準化する