BERT helps computers understand text better by reading words in context. We use it to teach a model to decide what category a piece of text belongs to.
BERT for text classification in PyTorch
from transformers import BertTokenizer, BertForSequenceClassification import torch # Load tokenizer and model tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2) # Prepare input text inputs = tokenizer('Your text here', return_tensors='pt', padding=True, truncation=True) # Get model output outputs = model(**inputs) # Extract logits for classification logits = outputs.logits
Use BertTokenizer to convert text into numbers the model understands.
BertForSequenceClassification is a BERT model with a classification head on top.
inputs = tokenizer('I love this product!', return_tensors='pt', padding=True, truncation=True) outputs = model(**inputs) logits = outputs.logits
inputs = tokenizer(['Good', 'Bad'], return_tensors='pt', padding=True, truncation=True) outputs = model(**inputs) logits = outputs.logits
This code classifies two sentences as positive or negative using BERT. It shows the loss and predicted labels.
from transformers import BertTokenizer, BertForSequenceClassification import torch from torch.nn.functional import cross_entropy # Sample data: texts and labels texts = ['I love this movie', 'This film is terrible'] labels = torch.tensor([1, 0]) # 1=positive, 0=negative # Load tokenizer and model tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2) # Prepare inputs inputs = tokenizer(texts, return_tensors='pt', padding=True, truncation=True) # Forward pass outputs = model(**inputs) logits = outputs.logits # Calculate loss loss = cross_entropy(logits, labels) # Predictions predictions = torch.argmax(logits, dim=1) print(f'Loss: {loss.item():.4f}') print(f'Predictions: {predictions.tolist()}')
BERT models are large; running on a GPU speeds up training and prediction.
Always tokenize and pad inputs to the same length for batch processing.
Output logits are raw scores; use softmax or argmax to get predicted classes.
BERT reads text with context to improve classification accuracy.
Use BertTokenizer and BertForSequenceClassification to build text classifiers easily.
Prepare inputs carefully and interpret logits to get predictions.
Practice
Solution
Step 1: Understand BERT's design
BERT reads words in context, meaning it looks at surrounding words to understand meaning better.Step 2: Compare with bag-of-words
Bag-of-words treats words independently, ignoring order and context, which limits understanding.Final Answer:
BERT understands the context of words in a sentence. -> Option AQuick Check:
Contextual understanding = A [OK]
- Thinking BERT uses fewer parameters
- Assuming BERT needs no preprocessing
- Believing BERT only works on short texts
Solution
Step 1: Identify correct class for model loading
BertForSequenceClassification is the class to load pretrained BERT models for classification tasks.Step 2: Check method usage
from_pretrained is the method to load pretrained weights by model name.Final Answer:
model = BertForSequenceClassification.from_pretrained('bert-base-uncased') -> Option CQuick Check:
Use BertForSequenceClassification.from_pretrained = A [OK]
- Using BertTokenizer to load model weights
- Trying to load model with torch.load without saving first
- Using nn.Sequential incorrectly for BERT
from transformers import BertTokenizer, BertForSequenceClassification
import torch
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=3)
inputs = tokenizer(['Hello world!', 'BERT is great.'], padding=True, return_tensors='pt')
outputs = model(**inputs)
logits = outputs.logits
print(logits.shape)Solution
Step 1: Understand batch size and labels
Input has 2 sentences, so batch size is 2. num_labels=3 means 3 classes.Step 2: Check output logits shape
Logits shape is (batch_size, num_labels), so (2, 3).Final Answer:
torch.Size([2, 3]) -> Option BQuick Check:
Batch size 2 and 3 labels = (2, 3) [OK]
- Confusing batch size and label dimension order
- Assuming output shape matches hidden size (768)
- Ignoring batch size in output shape
TypeError: forward() got an unexpected keyword argument 'input_ids'. What is the likely cause?
outputs = model(input_ids=inputs['input_ids'], attention_mask=inputs['attention_mask'])
Solution
Step 1: Analyze error message
The error says forward() got unexpected keyword 'input_ids', meaning the model does not accept this argument.Step 2: Identify model type mismatch
BertTokenizer does not have a forward method and does not accept input_ids; only BertForSequenceClassification does.Final Answer:
The model variable is a BertTokenizer, not BertForSequenceClassification. -> Option AQuick Check:
Wrong model type causes unexpected argument error = D [OK]
- Confusing tokenizer with model
- Assuming attention_mask is unsupported
- Thinking inputs dictionary is missing keys
Solution
Step 1: Understand class imbalance problem
Imbalanced classes cause the model to favor majority classes, hurting minority class accuracy.Step 2: Choose appropriate solution
Weighted loss assigns higher penalty to errors on minority classes, helping balance learning.Final Answer:
Use weighted loss function to give more importance to minority classes. -> Option DQuick Check:
Weighted loss helps with imbalance = C [OK]
- Removing attention_mask harms input understanding
- Reducing num_labels loses class info
- Freezing all layers limits fine-tuning benefits
Ready to prove it?
Pass the test and this pattern moves unknown
