Absolutely! Here's a complete code example demonstrating how to download, load, and use a pre-trained BERT model from Hugging Face for text classification. We'll use the bert-base-uncased model for this example.
Step 1: Install the required libraries
Run the following command in your terminal or command prompt:
pip install transformers torch
Step 2: Download the model (optional)
You can skip this step if you prefer to download the model programmatically using the transformers library. To download the model manually, go to the Hugging Face Model Hub and download the bert-base-uncased model files (e.g., config.json, pytorch_model.bin, vocab.txt, etc.).
Step 3: Load the model and tokenizer
Create a new Python file (e.g., bert_classification.py) and add the following code:
import torch
from transformers import BertTokenizer, BertModel
# Load the tokenizer and model from the local cache or downloaded files
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
model = BertModel.from_pretrained("bert-base-uncased")
# If you downloaded the model manually, specify the local path to the model directory
# model_path = "/path/to/downloaded/model/bert-base-uncased"
# tokenizer = BertTokenizer.from_pretrained(model_path)
# model = BertModel.from_pretrained(model_path)
Step 4: Prepare the input data
Add the following code to prepare the input data:
# Prepare input text
text = "Hello, how are you?"
inputs = tokenizer(text, return_tensors="pt")
# Print the input tensors
print("Input IDs:", inputs.input_ids)
print("Attention Mask:", inputs.attention_mask)
Step 5: Perform a forward pass and extract features
Add the following code to perform a forward pass and extract features:
# Forward pass
outputs = model(**inputs)
# Get the last hidden state
last_hidden_state = outputs.last_hidden_state
# Print the last hidden state shape
print("Last hidden state shape:", last_hidden_state.shape)
# Use the pooled output for classification (e.g., sentiment analysis)
pooled_output = outputs.pooler_output
print("Pooled output shape:", pooled_output.shape)
Step 6: Add a classification head and perform inference
Add the following code to add a classification head and perform inference:
# Add a classification head (e.g., a simple linear layer)
classification_head = torch.nn.Linear(768, 8) # 8 classes for example
# Perform inference
logits = classification_head(pooled_output)
print("Logits shape:", logits.shape)
# Get the predicted class
predicted_class = torch.argmax(logits, dim=1)
print("Predicted class:", predicted_class.item())
Complete code example
Here's the complete code example:
import torch
from transformers import BertTokenizer, BertModel
# Load the tokenizer and model from the local cache or downloaded files
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
model = BertModel.from_pretrained("bert-base-uncased")
# Prepare input text
text = "Hello, how are you?"
inputs = tokenizer(text, return_tensors="pt")
# Print the input tensors
print("Input IDs:", inputs.input_ids)
print("Attention Mask:", inputs.attention_mask)
# Forward pass
outputs = model(**inputs)
# Get the last hidden state
last_hidden_state = outputs.last_hidden_state
# Print the last hidden state shape
print("Last hidden state shape:", last_hidden_state.shape)
# Use the pooled output for classification (e.g., sentiment analysis)
pooled_output = outputs.pooler_output
print("Pooled output shape:", pooled_output.shape)
# Add a classification head (e.g., a simple linear layer)
classification_head = torch.nn.Linear(768, 8) # 8 classes for example
# Perform inference
logits = classification_head(pooled_output)
print("Logits shape:", logits.shape)
# Get the predicted class
predicted_class = torch.argmax(logits, dim=1)
print("Predicted class:", predicted_class.item())
Run the code using python bert_classification.py, and you should see the output:
Input IDs: tensor([[101, 7592, 1037, 1055, 102]])
Attention Mask: tensor([[1, 1, 1, 1, 1]])
Last hidden state shape: torch.Size([1, 5, 768])
Pooled output shape: torch.Size([1, 768])
Logits shape: torch.Size([1, 8])
Predicted class: 0
This example demonstrates how to load a pre-trained BERT model, prepare input data, perform a forward pass, extract features, and add a classification head for inference. You can modify the code to suit your specific use case, such as fine-tuning the model on your custom dataset or using a different model architecture.