setfit - Efficient few-shot learning with Sentence Transformers

Created at: 2022-06-30 15:10:15
Language: Python
License: Apache-2.0

🤗 Models & Datasets | 📖 Blog | 📃 Paper

SetFit - Efficient Few-shot Learning with Sentence Transformers

We introduce SetFit, an efficient and prompt-free framework for few-shot fine-tuning of Sentence Transformers. SetFit achieves high accuracy with little labeled data - for instance, with only 8 labeled examples per class on the Customer Reviews sentiment dataset, SetFit is competitive with fine-tuning RoBERTa Large on the full training set of 3k examples 🤯!

Compared to other few-shot learning methods, SetFit has several unique features:

  • 🗣 No prompts or verbalisers: Current techniques for few-shot fine-tuning require handcrafted prompts or verbalisers to convert examples into a format that's suitable for the underlying language model. SetFit dispenses with prompts altogether by generating rich embeddings directly from text examples.
  • 🏎 Fast to train: SetFit doesn't require large-scale models like T0 or GPT-3 to achieve high accuracy. As a result, it is typically an order of magnitude (or more) faster to train and run inference with.
  • 🌎 Multilingual support: SetFit can be used with any Sentence Transformer on the Hub, which means you can classify text in multiple languages by simply fine-tuning a multilingual checkpoint.

Getting started


Download and install setfit by running:

python -m pip install setfit

Training a SetFit model

setfit is integrated with the Hugging Face Hub and provides two main classes:

  • SetFitModel: a wrapper that combines a pretrained body from sentence_transformers and a classification head from scikit-learn
  • SetFitTrainer: a helper class that wraps the fine-tuning process of SetFit.

Here is an end-to-end example:

from datasets import load_dataset
from sentence_transformers.losses import CosineSimilarityLoss

from setfit import SetFitModel, SetFitTrainer

# Load a dataset from the Hugging Face Hub
dataset = load_dataset("emotion")

# Simulate the few-shot regime by sampling 8 examples per class
num_classes = 6
train_ds = dataset["train"].shuffle(seed=42).select(range(8 * num_classes))
test_ds = dataset["test"]

# Load SetFit model from Hub
model = SetFitModel.from_pretrained("sentence-transformers/paraphrase-mpnet-base-v2")

# Create trainer
trainer = SetFitTrainer(
    num_iterations=20, # The number of text pairs to generate

# Train and evaluate
metrics = trainer.evaluate()

# Push model to the Hub

For more examples, check out the notebooks/ folder.

Reproducing the results from the paper

We provide scripts to reproduce the results for SetFit and various baselines presented in Table 2 of our paper. Checkout the setup and training instructions in the scripts/ directory.

Developer installation

To run the code in this project, first create a Python virtual environment using e.g. Conda:

conda create -n setfit python=3.9 && conda activate setfit

Then install the base requirements with:

python -m pip install -e '.[dev]'

This will install datasets and packages like black and isort that we use to ensure consistent code formatting. Next, go to one of the dedicated baseline directories and install the extra dependencies, e.g.

cd scripts/setfit
python -m pip install -r requirements.txt

Formatting your code

We use black and isort to ensure consistent code formatting. After following the installation steps, you can check your code locally by running:

make style && make quality

Project structure

├── Makefile        <- Makefile with commands like `make style` or `make tests`
├──       <- The top-level README for developers using this project.
├── notebooks       <- Jupyter notebooks.
├── final_results   <- Model predictions from the paper
├── scripts         <- Scripts for training and inference
├── setup.cfg       <- Configuration file to define package metadata
├──        <- Make this project pip installable with `pip install -e`
├── src             <- Source code for SetFit
└── tests           <- Unit tests


  doi = {10.48550/ARXIV.2209.11055},
  url = {},
  author = {Tunstall, Lewis and Reimers, Nils and Jo, Unso Eun Seo and Bates, Luke and Korat, Daniel and Wasserblat, Moshe and Pereg, Oren},
  keywords = {Computation and Language (cs.CL), FOS: Computer and information sciences, FOS: Computer and information sciences},
  title = {Efficient Few-Shot Learning Without Prompts},
  publisher = {arXiv}, 
  year = {2022},
  copyright = {Creative Commons Attribution 4.0 International}}