Sub topic 5
The label matrix: sources by examples
This chapter assumes you can write basic Python and NumPy, and that you have seen the labeling functions from the previous chapter: small functions that return a class or abstain. You do not need probability beyond knowing what a vote is. The chapter covers how the votes from many labeling functions are stored in one table, what each cell means, and which mistakes in building that table cause silent errors later.
What the label matrix is
A labeling function (LF) looks at one text and returns a class or abstains. To use many LFs together, you run every LF on every text and store the results in a two-dimensional array called the label matrix, usually written L.
- Each row is one example (one text).
- Each column is one labeling function.
- Cell
L[i, j]holds the vote of LFjon examplei.
For n texts and m LFs, L has shape (n, m). Everything after this point in a weak supervision pipeline reads only this matrix: the diagnostics, the majority vote, and the label model. None of them see the raw text. So the matrix is the interface between the noisy sources and the rest of the pipeline.
Encoding votes and abstention
Each cell holds an integer. Classes are numbered 0 to k-1 for k classes, and abstention gets a value outside that range. The usual choice is -1, which is also what Snorkel uses.
| Cell value | Meaning |
|---|---|
| `-1` | The LF abstained: it has no opinion on this text |
| `0` | The LF voted for class 0 (here, negative) |
| `1` | The LF voted for class 1 (here, positive) |
Abstention is not a vote for "neutral" or "other". It means "this function does not apply here". Most LFs are written to be precise on a narrow pattern, so most cells in a typical matrix are -1. A matrix that is mostly abstentions is normal.
Building the matrix
The code below defines three LFs, applies them to four reviews, and checks the result. It uses int8 because the values are tiny and must be signed so that -1 is representable.
import re
import numpy as np
ABSTAIN, NEG, POS = -1, 0, 1
CARDINALITY = 2 # number of classes
def lf_positive_words(text):
return POS if re.search(r'\b(great|excellent|love)\b', text, re.I) else ABSTAIN
def lf_negative_words(text):
return NEG if re.search(r'\b(refund|broken|terrible)\b', text, re.I) else ABSTAIN
def lf_thanks(text):
return POS if 'thank' in text.lower() else ABSTAIN
lfs = [lf_positive_words, lf_negative_words, lf_thanks]
texts = [
'I love this phone, great battery',
'Arrived broken, I want a refund',
'Thank you, but it is terrible',
'It is a phone',
]
def build_label_matrix(texts, lfs):
# Start from ABSTAIN, so a cell that is never written means "no vote".
L = np.full((len(texts), len(lfs)), ABSTAIN, dtype=np.int8)
for i, text in enumerate(texts):
for j, lf in enumerate(lfs):
L[i, j] = lf(text)
return L
def check_label_matrix(L, cardinality):
assert L.ndim == 2, 'L must be two-dimensional'
bad = (L < ABSTAIN) | (L >= cardinality)
assert not bad.any(), 'found values outside {-1, 0, ..., k-1}'
L = build_label_matrix(texts, lfs)
check_label_matrix(L, CARDINALITY)
print(L)
# [[ 1 -1 -1]
# [-1 0 -1]
# [-1 0 1]
# [-1 -1 -1]]
voted = L != ABSTAIN
print('votes per example:', voted.sum(axis=1)) # [1 1 2 0]
print('votes per function:', voted.sum(axis=0)) # [1 2 1]
print('unlabeled rows:', np.flatnonzero(voted.sum(axis=1) == 0)) # [3]Reading the matrix
The four rows show the situations that every later step has to handle.
- Row 0 has one vote, from
lf_positive_words. The other two LFs abstain. There is nothing to combine. - Row 1 has one vote, from
lf_negative_words. - Row 2 has two votes that disagree:
lf_negative_wordssays negative because of "terrible", andlf_thankssays positive because of "Thank you". This is a conflict, and resolving conflicts is the reason combining methods exist. - Row 3 has no votes. The text "It is a phone" is not covered by any LF. No combining method can produce a label from zero votes, so such rows are either dropped from training or labeled some other way.
Reading column-wise, lf_negative_words voted on 2 of 4 texts. Reading row-wise tells you how much evidence each text has. Both views are used in the next chapter to compute coverage, overlap and conflict.
Errors that corrupt the matrix silently
Most bugs here do not raise exceptions. They produce a plausible matrix with wrong content.
Using 0 as the abstain value
If you initialize with np.zeros or let a function return 0 for "no opinion", every abstention becomes a vote for class 0. In a binary task with 0 as negative, this creates a flood of fake negative votes. Your majority vote will then be biased toward negative, and no error message will say so. Always initialize with the abstain constant, and keep class numbering and the abstain value in one place.
Returning `None` or `False`
In Python, a function that falls off the end returns None. Assigning None into an int8 array raises a TypeError, which is the good case. Returning False is worse: it converts to 0 and becomes a negative vote. Make every LF return one of the named constants on every path.
Unstable column order
The column index identifies the LF. If you build the matrix for the training set with one list of LFs and for the gold set with a differently ordered list, a label model trained on the first will misread the second. Keep a single lfs list, treat its order as part of the model, and store the names alongside the matrix.
lf_names = [lf.__name__ for lf in lfs]
print(lf_names) # ['lf_positive_words', 'lf_negative_words', 'lf_thanks']Non-deterministic or stateful LFs
An LF should return the same vote for the same text every time. An LF that uses a random sample, a changing external service, or internal counters will produce a different matrix on each run, and your diagnostics will not be reproducible. If a source is inherently random, such as an LLM sampled at nonzero temperature, run it once and save the result as a column rather than recomputing it.
Wrong cardinality
The label model needs to know how many classes there are. If you declare 2 classes but one LF returns 2, the check function above catches it. If you declare 3 classes but only ever see votes 0 and 1, no check can catch it, and the model will reserve probability for a class that no source ever predicts. Set the cardinality from the task definition, not from the data.
Storage and scale
For thousands of texts and a few dozen LFs, a dense int8 array is small. A matrix of 1,000,000 rows and 50 columns takes 50 MB. The cost that matters is not memory but LF runtime: a regex LF is cheap, while an LF that calls a model or an API can dominate the whole pipeline. This is why you compute L once, save it, and reuse it while you tune the combining step.
Mostly-abstaining matrices can also be stored sparsely, but most label model implementations expect a dense array, so convert back before fitting. Do not store only the non-abstain cells unless you also store the shape, because the number of rows with no votes is itself information.
Changing the matrix as the project grows
The matrix is cheap to extend in two directions.
- Adding an LF adds a column. You only need to run the new LF over the existing texts, then stack its column onto
L. Existing columns are unchanged. - Adding texts adds rows. You must run every LF on the new texts, using the same LF list and order.
Edits to an existing LF are different. If you change a regex, its whole column is stale and must be recomputed. A common practice is to keep a version tag per LF with the saved matrix, so a stale column is detectable.
Exercise
A teammate builds the label matrix with L = np.zeros((n, m), dtype=int) and then fills in only the cells where an LF fires, leaving the others untouched. The task is binary with 0 for negative and 1 for positive. What goes wrong, and how do you fix it?
Show answer
Every cell that was never written stays 0, which the downstream code reads as a vote for negative, so abstentions turn into fake negative votes. This inflates apparent coverage and conflict and biases majority vote toward negative. The fix is to initialize with np.full((n, m), ABSTAIN, dtype=np.int8) where ABSTAIN = -1, so unwritten cells mean "no vote".
Exercise
Using the matrix L printed in this chapter, which rows would a majority vote with tie-abstention be unable to label confidently, and why? Name the row index for each reason.
Show answer
Row 3 has no votes at all, so there is nothing to count. Row 2 has one vote for each class, which is a tie, so a tie-abstaining majority vote returns no label. Rows 0 and 1 each have a single vote and are labeled by it.
Exercise
You add a fourth LF to an existing project and rerun only the new LF on the training texts. What must you also do before fitting a label model, and what must you check about the gold set matrix?
Show answer
Append the new LF's column to the saved training matrix, in the same position as in the LF name list, and confirm the cardinality and value range still hold. For the gold set, build its matrix with the same four LFs in the same order, because the label model reads columns by position.