Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Few-Shot Text Classifier with Scikit-LLM

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Scikit-LLM lets you combine the power of large language models with the familiar scikit-learn API. This guide shows you how to build a few-shot text classifier—one that learns from just a handful of labeled examples—using ZeroShotGPTClassifier and FewShotGPTClassifier. You'll be able to classify text into custom categories without training a traditional model or writing complex prompts.

What You'll Need

  • Python 3.8 or newer installed on your machine.
  • An OpenAI API key (the library uses GPT models by default). You can get one from OpenAI's platform.
  • Basic familiarity with Python and scikit-learn (fitting, predicting, evaluation).
  • Install the required packages: scikit-llm, scikit-learn, and openai.

Step-by-Step

  1. Install dependencies. Run the following in your terminal:
    pip install scikit-llm scikit-learn openai
  2. Set your OpenAI API key. In your Python script, set it as an environment variable or directly:
    import os
    os.environ["OPENAI_API_KEY"] = "your-api-key-here"
    Keep the key secret—don't commit it to version control.
  3. Import the classifiers. Scikit-LLM provides two main classes:
    from skllm import ZeroShotGPTClassifier, FewShotGPTClassifier
  4. Prepare your data. For few-shot classification, you need a small set of labeled examples. For instance, if classifying movie reviews as positive or negative:
    X_train = [
        "I loved this film, it was amazing!",
        "The plot was boring and predictable.",
        "Great acting and stunning visuals.",
        "Waste of time, I fell asleep."
    ]
    y_train = ["positive", "negative", "positive", "negative"]
    
    X_test = [
        "The movie was fantastic, I recommend it.",
        "It was dull and I didn't care about the characters."
    ]
  5. Create a Zero-Shot classifier first (optional). This works without any training data—just specify candidate labels:
    clf = ZeroShotGPTClassifier()
    clf.fit(None, ["positive", "negative"])  # No training data needed
    preds = clf.predict(X_test)
    This is a good baseline. If it's accurate enough, you may not need few-shot.
  6. Create a Few-Shot classifier. For better accuracy with a few examples, use FewShotGPTClassifier:
    clf = FewShotGPTClassifier()
    clf.fit(X_train, y_train)
    preds = clf.predict(X_test)
    print(preds)  # Output: ['positive', 'negative']
    The classifier internally selects the most relevant examples from your training set to include in the prompt for each test sample.
  7. Evaluate performance. If you have true labels for the test set, use scikit-learn metrics:
    from sklearn.metrics import accuracy_score
    y_true = ["positive", "negative"]
    print(f"Accuracy: {accuracy_score(y_true, preds):.2f}")
  8. Customize the model (optional). You can change the underlying GPT model or set a max number of examples:
    clf = FewShotGPTClassifier(model="gpt-4o-mini", max_labels=3)
    The max_labels parameter limits how many training examples are used per prediction, which can reduce cost.
  9. Handle multi-class problems. The classifier works with any number of classes; just provide labels accordingly in y_train.
  10. Save and load the model. Use joblib or pickle to persist the fitted classifier for later use:
    import joblib
    joblib.dump(clf, "classifier.joblib")
    clf_loaded = joblib.load("classifier.joblib")

Common Mistakes

  • Not setting the API key. The library will raise an error if the key is missing. Always set it before fitting.
  • Using too many training examples. Few-shot means “few”—typically 5 to 20 per class. Using hundreds will increase cost and may exceed token limits.
  • Inconsistent label formatting. Labels like “Positive” and “positive” are treated as different classes. Stick to one case and format.
  • Forgetting to install scikit-learn. Scikit-LLM depends on it; if you get import errors, reinstall both.
  • Assuming zero-shot is enough. Zero-shot can be surprisingly good, but for domain-specific terms, few-shot usually wins. Test both.

Tips

  • Start with ZeroShotGPTClassifier to get a baseline. Only add few-shot examples if accuracy is insufficient.
  • Choose diverse training examples—cover different phrasings, lengths, and edge cases. This helps the model generalize.
  • Keep your training examples concise. Long examples eat up tokens and may confuse the model.
  • Use the max_labels parameter to control cost. For a 2-class problem, 2-3 examples per class often suffice.
  • If you have a large test set, process it in batches to avoid hitting rate limits.
  • Monitor your OpenAI usage; each prediction sends a prompt to the API, so costs can add up.

Troubleshooting

  • ImportError: No module named 'skllm' – Install the package: pip install scikit-llm. If it persists, try installing in a fresh virtual environment.
  • AuthenticationError: Incorrect API key – Double-check that the key is set correctly and has not expired. Test it with a simple OpenAI API call.
  • RateLimitError – You're sending too many requests. Add a sleep between predictions or reduce the number of test samples per run.
  • Token limit exceeded – Your training examples are too long. Shorten them or reduce max_labels.
  • Predictions are all the same label – This often means the model isn't distinguishing classes. Try more diverse training examples or switch to a more capable model.
  • Output labels differ from training labels – The model may output variations like “positive.” Ensure your labels are simple and consistent; you can also map outputs manually.

Frequently Asked Questions

What is the difference between ZeroShotGPTClassifier and FewShotGPTClassifier?

Zero-shot requires no training data; you just provide candidate labels. Few-shot uses a small set of labeled examples to guide the model, which usually improves accuracy for specific tasks.

How many training examples do I need?

Typically 2-5 per class is enough for simple tasks. For more nuanced classification, 10-20 per class may be needed. More than that, consider fine-tuning a traditional model instead.

Can I use a local LLM instead of OpenAI?

Scikit-LLM is built for OpenAI models. For local models, you would need to adapt the code or use a different library.

How much does it cost?

Costs depend on the model and number of tokens. Each prediction sends a prompt with your training examples, so costs scale with test set size and example length. Use max_labels to control usage.

Can I use it for multi-label classification?

Not directly. The classifier assigns a single label per sample. For multi-label, you'd need to train one classifier per label or use a different approach.

Is it better than fine-tuning a BERT model?

For very small datasets, few-shot GPT is often more accurate and easier to set up. For larger datasets (hundreds of examples), fine-tuning a smaller model may be cheaper and faster.