Sub topic 10
Training a classifier on weak labels
This chapter assumes you can train a scikit-learn text classifier, you know what a label matrix and a label model are from the previous chapters, and you are comfortable with precision, recall and F1. It covers the last step of the pipeline: turning the label model's output into a classifier you can deploy.
Why train an end model at all
The label model already produces a probability for each example, so you could stop there. In practice you don't, for three reasons.
- Coverage. Labeling functions abstain on many examples. The label model can only label text that at least one function fires on. A classifier labels everything.
- Generalization. Labeling functions look at narrow signals such as a keyword or a regex. An end model sees the whole text, for example every n-gram or a fine-tuned transformer's representation. It can learn that "battery died in a week" is negative even though no function matched "battery".
- Cost at inference time. Labeling functions may call a knowledge base or an LLM. The end model is one cheap forward pass.
The end model is called that because it comes at the end of the pipeline. It is an ordinary supervised classifier. The only difference is that its training labels are noisy and probabilistic.
Handling uncovered examples
When every function abstains on an example, the label model has no evidence. Most implementations return a uniform distribution, such as [0.5, 0.5], or an arbitrary class. Training on those rows teaches the classifier noise.
The standard fix is to compute a coverage mask from the label matrix and keep only covered rows:
covered = (L != ABSTAIN).any(axis=1)Dropping uncovered rows has a cost. If the functions only fire on easy, keyword-heavy examples, the training set no longer looks like your real data. The end model may then be weak on exactly the texts the functions missed. Two things help. First, measure total coverage before training, using the diagnostics from earlier in the tutorial. Second, add functions aimed at the uncovered examples, instead of lowering your standards for what counts as a label.
Hard labels or soft labels
You have three ways to pass the label model's output to the classifier.
| Option | How | Strength | Weakness |
|---|---|---|---|
| Hard labels | Take `argmax` of the probabilities | Works with any classifier | Throws away confidence. A 0.51 label counts the same as a 0.99 label. |
| Hard labels with a threshold | Keep only rows where the top probability is at least a cutoff | Removes the most doubtful rows | Shrinks the training set and can skew the class mix |
| Soft labels | Train on the full probability vector | Uses all the information. Doubtful rows pull the model less. | Needs a loss that accepts probability targets |
Soft labels are the usual choice. Training with cross-entropy against a probability vector is called a noise-aware loss. The loss for one example is the expected cross-entropy under the label model's distribution. If the label model says 0.8 positive, the example contributes 0.8 of a positive example and 0.2 of a negative one.
Many frameworks support this directly. PyTorch's CrossEntropyLoss accepts class probabilities as targets. Scikit-learn classifiers do not, but you can get the same effect with sample weights.
A runnable example
The code below fits a logistic regression on soft labels. It duplicates every covered example, once per class, and weights each copy by that class's probability. This is mathematically the same as soft-target cross-entropy. The probabilities are hard-coded to stand in for the label model's output.
import numpy as np
from scipy.sparse import vstack
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
ABSTAIN, NEG, POS = -1, 0, 1
texts = [
'I love this phone, great battery',
'Arrived broken, I want a refund',
'Excellent screen and fast shipping',
'Terrible build, the hinge is broken',
'Great value for the price',
'It is a phone',
'Battery died after a week, refund please',
'Love the camera',
]
# Label matrix: one column per labeling function.
L = np.array([
[POS, ABSTAIN, ABSTAIN],
[ABSTAIN, NEG, ABSTAIN],
[POS, ABSTAIN, ABSTAIN],
[ABSTAIN, NEG, ABSTAIN],
[POS, ABSTAIN, ABSTAIN],
[ABSTAIN, ABSTAIN, ABSTAIN],
[ABSTAIN, NEG, ABSTAIN],
[POS, ABSTAIN, POS],
])
# Columns are P(NEG), P(POS), as a label model would return them.
probs = np.array([
[0.10, 0.90], [0.85, 0.15], [0.20, 0.80], [0.90, 0.10],
[0.30, 0.70], [0.50, 0.50], [0.80, 0.20], [0.05, 0.95],
])
covered = (L != ABSTAIN).any(axis=1)
train_texts = [t for t, c in zip(texts, covered) if c]
train_probs = probs[covered]
# Fit the vectorizer on training text only.
vec = TfidfVectorizer(ngram_range=(1, 2))
X = vec.fit_transform(train_texts)
n = X.shape[0]
# Soft labels as weighted copies: one copy per class, weighted by P(class).
X_soft = vstack([X, X])
y_soft = np.array([NEG] * n + [POS] * n)
w_soft = np.concatenate([train_probs[:, 0], train_probs[:, 1]])
clf = LogisticRegression(max_iter=1000)
clf.fit(X_soft, y_soft, sample_weight=w_soft)
gold_texts = ['Love it, great phone', 'Broken screen, want a refund']
print(clf.predict(vec.transform(gold_texts)))Two details matter here. The vectorizer is fit on the training texts only, so no information from the evaluation data leaks into it. The coverage mask is applied before the soft labels are built, so the uniform [0.5, 0.5] row for "It is a phone" never reaches the classifier.
Making the end model learn more than the functions
The end model can only beat the labeling functions if it uses information they don't. If its features are the same keywords your functions match, it learns to reproduce them. It will have the same coverage and the same blind spots, with extra variance.
Some ways to avoid this:
- Use features or representations that go beyond the functions' patterns, such as embeddings, character n-grams or a pretrained transformer.
- Keep the functions' decisive patterns out of the input when you can do so without harm. Some teams mask matched keywords during training so the model must find other evidence. This is a deliberate trade-off. Test it on the gold set before adopting it.
- Write functions that use signals the model cannot see, such as metadata, a knowledge base lookup or an LLM call. The end model then learns to approximate that hidden signal from the text alone.
Practical points
- Class balance. The label model's output can be badly skewed, because functions for one class often fire more than functions for another. Check the class distribution of
argmax(probs)on covered rows. If it differs sharply from what you expect in real data, reweight classes or fix the functions. - Model capacity. A large model trained for many epochs on noisy labels will eventually memorize the noise. Use early stopping on a held-out set, weight decay, and fewer epochs than you would with clean labels.
- Held-out data. Keep a validation set for early stopping that is separate from the gold test set. Tuning on the test set makes your final numbers too optimistic.
- Retraining. When you change a labeling function, refit the label model and retrain the end model. Do not reuse old probabilities.
Exercise
A label model returns [0.5, 0.5] for every example on which all labeling functions abstain. A teammate keeps those rows and trains with soft labels, arguing that a 50/50 label "contributes nothing". Why is this still a mistake, and what should be done instead?
Show answer
A 50/50 soft label does not contribute nothing. Each such row adds a copy of its text to both classes with equal weight, which pushes the model toward predicting 0.5 for the kinds of text the functions miss. It also adds noise and slows training. Compute a coverage mask from the label matrix ((L != ABSTAIN).any(axis=1)), drop uncovered rows before training, and then work on raising coverage by writing functions for the missed examples.