Ravindra BagaleCourses & study guides English Track your progress

50. Tiny Text Classifier with a Transformer Intro in PyTorch

Data Science

50.3 Mean-Embed Classifier

50.3 Mean-embed classifier

Minimal net — full multi-head attention आधी embeddings काम करताना दाखवा.

हे का शिकायचं?

Why. Minimal net दाखवते की embeddings काम करतात — full multi-head attention code आधी.

हे काय आहे?

What. Embedding → pad mask → mean pool → Linear to 1 logit. (Stretch: नंतर mean pool जागी nn.TransformerEncoder.)

कसं करायचं?

How.

MeanEmbedClassifier define करा

  1. nn.Embedding
  2. Non-pad positions average
  3. Linear to 1 output
import torch
import torch.nn as nn

class MeanEmbedClassifier(nn.Module):
    def __init__(self, vocab_size=8, dim=16):
        super().__init__()
        self.emb = nn.Embedding(vocab_size, dim, padding_idx=0)
        self.fc = nn.Linear(dim, 1)
    def forward(self, token_ids):
        x = self.emb(token_ids) # (B, T, D)
        mask = (token_ids != 0).float().unsqueeze(-1)
        summed = (x * mask).sum(dim=1)
        counts = mask.sum(dim=1).clamp(min=1.0)
        return self.fc(summed / counts)

print(MeanEmbedClassifier())