Building a Customer Intent Classifier with SetFit - Complete Guide
Traditional text classification models often require thousands of labeled examples to achieve high accuracy. For customer intent detection—where new categories emerge frequently—gathering large datasets is time-consuming and expensive.
SetFit (Sentence Transformer Fine-Tuning) solves this challenge by leveraging efficient few-shot learning. By combining contrastive sentence transformer tuning with a lightweight classification head, SetFit achieves high accuracy with as few as 8 to 20 examples per class.
How SetFit Few-Shot Classification Works
SetFit operates in two distinct phases to maximize embedding separation without requiring complex prompt engineering:
- Sentence Transformer Fine-Tuning: The model takes pairs of sentences (positive and negative pairs based on intent labels) and fine-tunes a pre-trained sentence transformer via contrastive learning to cluster similar intents closely in vector space.
- Classifier Training: Once the sentence embeddings are optimized for intent separation, a simple and efficient classification head (such as Logistic Regression) is trained on the resulting sentence vectors.
- Inference Pipeline: Incoming customer queries are embedded using the fine-tuned transformer and classified instantly by the trained head with minimal latency.
Python Implementation for Customer Intent Detection
Here is a complete Python script demonstrating how to train and evaluate a SetFit classifier for customer intent detection using the setfit library:
from setfit import SetFitModel, SetFitTrainer
from datasets import Dataset
def train_customer_intent_classifier():
# 1. Prepare few-shot training data
train_data = {
"text": [
"Where is my order?", "Track my package please", "Has my shipment shipped?",
"I want a refund", "How do I return this item?", "Process my money back",
"Reset my password", "I cannot log into my account", "Change my login credentials"
],
"label": [0, 0, 0, 1, 1, 1, 2, 2, 2] # 0: Shipping, 1: Refunds, 2: Account
}
train_dataset = Dataset.from_dict(train_data)
# 2. Load a lightweight Sentence Transformer model
model_id = "sentence-transformers/all-MiniLM-L6-v2"
print(f"Loading base model: {model_id}...")
model = SetFitModel.from_pretrained(model_id)
# 3. Initialize the SetFit trainer
trainer = SetFitTrainer(
model=model,
train_dataset=train_dataset,
loss_class="sentence_transformers.losses.CosineSimilarityLoss",
batch_size=16,
num_iterations=20,
num_epochs=1
)
# 4. Train and save the model
print("Training SetFit intent classifier...")
trainer.train()
# 5. Test inference
sample_queries = [
"Can you help me track my delivery?",
"I need a refund for my damaged purchase",
"Forgot my password, need help"
]
predictions = model.predict(sample_queries)
for query, pred in zip(sample_queries, predictions):
print(f"Query: '{query}' --> Predicted Intent Class: {pred}")
return model
if __name__ == "__main__":
trained_model = train_customer_intent_classifier()
Intent Classification Best Practices
When deploying customer intent classifiers in production environments, keep these engineering guidelines in mind:
- Curate Diverse Few-Shot Examples: Ensure your few-shot samples cover different phrasing styles, slang, and common typos for each customer intent category.
- Tune Iteration Parameters: Adjust
num_iterationsduring training to generate balanced positive/negative sentence pairs without overfitting small training sets. - Establish Confidence Thresholds: Set probability thresholds on classification outputs to route low-confidence customer queries to human support agents.