Sub topic 3
Writing Labeling Functions That Can Abstain
Prerequisites
This chapter assumes you can write basic Python, read simple regular expressions, and compute precision and recall. You should also know why a text classifier needs labeled examples. Earlier chapters explained why labeled text is scarce and why many noisy sources can stand in for a few clean labels. Here you write those sources.
What a labeling function is
A labeling function (LF) is a small program that takes one example and returns either a class or a special value meaning "no opinion". It is deliberately imperfect. You expect it to be wrong on some of the examples it votes on, and you expect it to say nothing on many others.
For a binary sentiment task, the contract looks like this:
- Input: one raw text.
- Output:
POS(1),NEG(0), orABSTAIN(-1). - No side effects, and no access to the gold label.
The constant for abstaining is a convention. Snorkel uses -1, and this chapter does too. Any value outside the class set works, provided every LF uses the same one.
Why abstaining matters
An LF that always answers is forced to guess on examples it knows nothing about. A guess adds noise, and the noise has a pattern. A function return POS if 'great' in text else NEG labels every text without "great" as negative. Those labels are wrong whenever a neutral or positive review avoids that word. Abstaining says that the LF has no evidence either way.
Abstention also gives you a precision and coverage trade-off, which is the main design decision for each LF:
- A narrow, precise rule votes rarely and is usually right.
- A broad rule votes often and is right less often.
Weak supervision works best with a mix of the two. The later combination step can weigh a broad LF less than a narrow one, but only if the broad one abstains where it has no signal.
Common sources for labeling functions
| Source | Example rule | Typical profile |
|---|---|---|
| Keyword or regex | Text contains "refund" | High precision, low coverage |
| Structural cue | Text ends with "!" | Low precision, medium coverage |
| Text statistics | Fewer than 4 words | Low precision, high coverage |
| Lexicon or knowledge base | Company name appears in a list | Depends on list quality (see the distant supervision chapter) |
| Existing model | A pretrained classifier is confident | Medium precision, high coverage, risk of inherited bias |
Heuristics from annotation guidelines are a good starting point. If your guidelines say "complaints mention returns or defects", each of those cues is a candidate LF.
A first set of functions with guards
The code below defines three LFs, including a guard that abstains when a positive word is negated. It then measures each LF on a tiny hand-labeled set. The measurements are coverage (the share of examples where the LF votes) and accuracy on the covered examples.
import re
ABSTAIN, NEG, POS = -1, 0, 1
POSITIVE = re.compile(r"\b(great|excellent|love[ds]?)\b", re.I)
NEGATIVE = re.compile(r"\b(refund|broken|terrible)\b", re.I)
NEGATED_POSITIVE = re.compile(r"\b(not|never|no)\s+(\w+\s+)?(great|excellent)\b", re.I)
def lf_positive_words(text):
if NEGATED_POSITIVE.search(text):
return ABSTAIN # guard: "not great" is not positive evidence
return POS if POSITIVE.search(text) else ABSTAIN
def lf_negative_words(text):
return NEG if NEGATIVE.search(text) else ABSTAIN
def lf_negated_positive(text):
return NEG if NEGATED_POSITIVE.search(text) else ABSTAIN
lfs = [lf_positive_words, lf_negative_words, lf_negated_positive]
dev = [
("Excellent screen", POS),
("The hinge is broken", NEG),
("Not great at all", NEG),
("Works fine and I am happy", POS),
("Terrible battery", NEG),
("Great phone, but the charger arrived broken", NEG),
]
for lf in lfs:
votes = [(lf(text), gold) for text, gold in dev if lf(text) != ABSTAIN]
coverage = len(votes) / len(dev)
correct = sum(vote == gold for vote, gold in votes)
accuracy = correct / len(votes) if votes else float("nan")
print(f"{lf.__name__:<22} coverage={coverage:.2f} accuracy={accuracy:.2f}")Running it prints:
lf_positive_words coverage=0.33 accuracy=0.50
lf_negative_words coverage=0.50 accuracy=1.00
lf_negated_positive coverage=0.17 accuracy=1.00Read these numbers as follows:
lf_positive_wordsvotes on two texts and is wrong on the mixed review. Its accuracy of 0.50 rests on two votes, so it is a weak estimate.lf_negative_wordsis accurate here, but all its votes are for one class.lf_negated_positivefires only once. It earns its place because the guard inlf_positive_wordswould otherwise have turned "Not great at all" into a wrong positive vote.- "Works fine and I am happy" receives no vote from any LF. That is acceptable. Pushing coverage to 100% with a default answer would add exactly the noise abstention avoids.
Design rules that prevent common errors
Return a class only on positive evidence
Write the condition under which the LF is confident, and let everything else fall through to ABSTAIN. Avoid else NEG branches unless "no match" is itself strong evidence for the negative class, which is rare in text.
Keep each function about one idea
A single LF that mixes five patterns is hard to debug, and its accuracy is an average over unlike behaviors. Split it. Five small LFs give you five separate accuracy and coverage numbers, which the diagnostics in the next chapters use.
Handle context that flips meaning
Negation ("not great"), questions ("is it any good?"), quotation ("he said it was terrible, but...") and sarcasm all reverse or cancel keyword evidence. Cheap guards, as shown above, remove the most common cases. Perfect handling is not needed, because the LF is allowed to be noisy.
Cover both classes
If every LF votes for one class, the weak labels show that class far more than the other, and a classifier trained on them will predict it too often. Write LFs for each class, even if one class is easier to describe.
Normalize input inside the function
Use case-insensitive matching, word boundaries (\b) and, if needed, Unicode normalization. Without word boundaries, 'no' in text matches "know" and "notebook". A substring test is the most frequent source of silent false votes.
Make LFs deterministic and fast
An LF should return the same output for the same text. A function that calls a network service without caching, or that depends on random state, makes later debugging impossible. You will run each LF over the whole unlabeled corpus, and you will re-run it every time you edit it.
The most common mistake: a function that never abstains
Consider this version:
def lf_bad(text):
return POS if "great" in text.lower() else NEGIt has 100% coverage and looks productive. It also says "negative" for "Works fine and I am happy" and for "Greatly disappointed" in the wrong direction as well, since the substring test matches "Greatly". On a typical review corpus, most texts do not contain "great", so this function mainly produces false negatives and crowds out the legitimate negative LFs in any vote. Compare it with lf_positive_words, which has lower coverage and every vote backed by evidence.
A quick check catches this error. If an LF's coverage is near 100%, ask what evidence it uses for the examples at the far end of the corpus. If the answer is "none", it should abstain there.
Where this leads
Applying each LF to every text gives a table with one row per text and one column per LF. That table is the label matrix, and the next chapter builds it. Coverage, overlap and conflict measured on the matrix tell you which LFs to fix, split or drop before any combination step.
Exercise
The LF def lf_short(text): return NEG if len(text.split()) < 4 else POS has 100% coverage. Rewrite it so it abstains where it has no evidence, and explain in one or two sentences why the rewrite helps.
Show answer
One rewrite is def lf_short(text): return NEG if len(text.split()) < 4 else ABSTAIN. The original labels every text of four or more words as positive, although length says nothing about positive sentiment, so it adds a large block of unreliable POS votes. The rewrite votes only where the short-length heuristic has some basis and abstains elsewhere. The cost is lower coverage, and that is the intended trade for higher precision. You may also drop the LF if a check on a dev set shows that short texts are not mostly negative.
Exercise
A teammate's LF is def lf_no(text): return NEG if 'no' in text.lower() else ABSTAIN. Name two ways it produces wrong votes and show a fix.
Show answer
The substring test matches inside other words ("know", "notebook", "casino"), and it also fires on harmless uses such as "no problems at all", which is positive. A fix is re.compile(r"\bno\b(?!\s+(problem|issue|complaint)s?)", re.I) used as return NEG if pattern.search(text) else ABSTAIN. The word boundaries stop matches inside longer words, and the negative lookahead abstains on common positive phrases. Even with these guards the function is broad, so measure its accuracy on a dev set before keeping it.