Relation extraction: the direction is part of the answer
关系抽取
Build a directional lexical classifier, distinguish distant supervision from sentence evidence, and evaluate relation families.
relation-extractionThe right two entities can still give the wrong answer
In the invented sentence Ava works for Birch, assume Ava is a person and Birch an employer. Given e1=Ava and e2=Birch, the relation points from e1 to e2. Swap the two supplied arguments and the direction changes, even though the sentence is identical. Finding both names does not finish the task.
Relation extraction assigns relations to selected arguments using text and a declared schema. The arguments need not be named entities: SemEval-2010 Task8 supplies two marked nominals and asks for their relation and direction. Its annotation policy also excludes specified speculative and negated cases. A different task may instead retain such cases with explicit qualifiers. Task and annotation scope
This article’s invented schema has employment and location families, two directions for each, and other: five labels. These are not the benchmark’s nine relation families. Entity IDs and spans are supplied; the program learns a small lexical classifier, not a complete entity detector or knowledge-base population system.
Keep argument order inside the representation
Define the unit before pooling evidence
For each sentence, record whether e1 occurs first or second, the tokens between the two spans, and conjunctions of those tokens with argument order. Exclude entity surface tokens to avoid memorizing names. Sum these features over the supplied sentences for one ordered entity pair:
This is an explicit count-pooling choice. Repeating a sentence doubles its feature contribution; it is not independent corroboration. The entity IDs group evidence but are not input features. An unordered pair key is used only to prevent the same pair, including its reversed presentation, from leaking across train/test splits.
Mintz et al.‘s2009 system aggregates features from sentences mentioning an entity pair and trains a multiclass logistic regression model with distant supervision. It motivates examining pooled evidence, but our supplied features and labels are a separate teaching setup. Architecture and lexical features, §§4–5.1
Linear logits and a normalized objective
For D features and K=5 classes, let W have shape D×K and b contain K biases. The column w_k scores class k. Softmax normalizes over the declared labels:
With one supplied gold label y_i per bag, use mean cross-entropy over N training bags. Subtract each row’s maximum logit before exponentiation; compute the loss from shifted logits without taking the logarithm of an underflowed probability.
If Y is the one-hot gold matrix, the complete gradients are:
At zero weights and biases, all five classes have probability1/5 and each bag’s loss is log5. For one bag with features [1,2] and gold class0, the bias gradient is[-4/5,1/5,1/5,1/5,1/5]. The weight gradient multiplies that row by each feature value. This hand case and every parameter of a separate25-parameter fixture are checked.
Weak labels are a different kind of evidence
A knowledge base may say that a person works for a company, while a sentence containing both names merely says they met. Mintz et al. describe the noisy distant-supervision assumption and combine features across occurrences. A database relation does not turn every co-occurrence into a sentence-level assertion. Distant supervision, §4
Likewise, absence from an incomplete knowledge base is not proof of other. Before training, decide whether an absent relation is unknown, an explicitly annotated negative, or a closed-world assumption. The program below receives explicit synthetic labels; it does not silently manufacture negatives from missing database entries.
Fit a complete directional classifier
Use Python3.12 and NumPy1.26. Six invented training pairs provide works for, is in and met templates. The three test pairs use different entity IDs but reuse those templates. A perfect result here checks the implemented mechanics, not semantic generalization to unseen language.
"""Original directed relation classifier with entity-pair bags and family metrics."""
from collections import Counter
import json,math
import numpy as np
LABELS=('employment:e1-e2','employment:e2-e1','location:e1-e2','location:e2-e1','other')
def group_key(record):
ids=[record.get(k) for k in ('e1','e2')]
if any(not isinstance(x,str) or not x for x in ids) or ids[0]==ids[1]:raise ValueError('distinct stable entity IDs required')
return tuple(sorted(ids))
def features(record):
group_key(record);rows=record.get('sentences')
if not isinstance(rows,list) or not 1<=len(rows)<=50:raise ValueError('one to50 sentences required')
counts=Counter()
for row in rows:
tokens=row['tokens'];spans=[row['span1'],row['span2']]
if not isinstance(tokens,list) or not 1<=len(tokens)<=100 or any(not isinstance(w,str) or not w for w in tokens):
raise ValueError('one to100 nonempty tokens required')
for span in spans:
if len(span)!=2 or any(type(x) is not int for x in span) or not 0<=span[0]<span[1]<=len(tokens):raise ValueError('invalid entity span')
a,b=sorted(spans)
if a[1]>b[0]:raise ValueError('entity spans must not overlap')
order='first' if spans[0]==a else 'second';counts['order:'+order]+=1
# Entity surface tokens are intentionally excluded, avoiding name memorization.
for word in tokens[a[1]:b[0]]:
counts['between:'+word.casefold()]+=1;counts['directed:'+order+':'+word.casefold()]+=1
return counts
def vocabulary(records):
return ['<UNK>']+sorted(set().union(*(features(r).keys() for r in records)))
def transform(records,vocab):
if not vocab or vocab[0]!='<UNK>' or len(set(vocab))!=len(vocab):raise ValueError('unique training vocabulary with UNK required')
index={w:i for i,w in enumerate(vocab)};x=np.zeros((len(records),len(vocab)))
for row,record in enumerate(records):
for term,count in features(record).items():x[row,index.get(term,0)]+=count
return x
def objective(x,y,w,b):
x,y,w,b=np.asarray(x,dtype=float),np.asarray(y),np.asarray(w,dtype=float),np.asarray(b,dtype=float)
if x.ndim!=2 or not len(x) or w.shape!=(x.shape[1],len(LABELS)) or b.shape!=(len(LABELS),):raise ValueError('feature/model shapes')
if y.shape!=(len(x),) or y.dtype.kind not in 'iu' or np.any(y<0) or np.any(y>=len(LABELS)):raise ValueError('class indices')
if any(not np.isfinite(a).all() or np.any(np.abs(a)>1e100) for a in (x,w,b)):raise ValueError('finite bounded arrays required')
scores=x@w+b;shifted=scores-scores.max(axis=1,keepdims=True);z=np.exp(shifted).sum(axis=1,keepdims=True)
probabilities=np.exp(shifted)/z;loss=float(np.mean(np.log(z[:,0])-shifted[np.arange(len(x)),y]))
residual=probabilities.copy();residual[np.arange(len(x)),y]-=1;residual/=len(x)
return loss,x.T@residual,residual.sum(axis=0),probabilities
def fit(records,labels,steps=80):
if len(labels)!=len(records) or any(y not in LABELS for y in labels):raise ValueError('one supported label per bag required')
if type(steps) is not int or not 0<=steps<=1000:raise ValueError('steps must be0..1000')
vocab=vocabulary(records);x=transform(records,vocab);y=np.array([LABELS.index(c) for c in labels],dtype=int)
w=np.zeros((len(vocab),len(LABELS)));b=np.zeros(len(LABELS));trace=[]
for step in range(steps+1):
loss,gw,gb,_=objective(x,y,w,b);trace.append(loss)
if step==steps:break
rate=1.
for _ in range(40):
nw,nb=w-rate*gw,b-rate*gb;nl,_,_,_=objective(x,y,nw,nb)
if nl<=loss-1e-4*rate*float(np.sum(gw*gw)+gb@gb):w,b=nw,nb;break
rate*=.5
else:raise ArithmeticError('line search failed')
return {'vocabulary':vocab,'weights':w,'bias':b,'loss_trace':trace}
def predict(model,records):
x=transform(records,model['vocabulary'])
if not len(x):return [],[]
_,_,_,p=objective(x,np.zeros(len(x),dtype=int),model['weights'],model['bias'])
return [LABELS[i] for i in np.argmax(p,axis=1)],p.tolist()
def metrics(gold,predicted):
if len(gold)!=len(predicted) or any(x not in LABELS for x in list(gold)+list(predicted)):raise ValueError('aligned supported labels required')
scores={}
for family in ('employment','location'):
g=sum(x.startswith(family+':') for x in gold);p=sum(x.startswith(family+':') for x in predicted)
tp=sum(a==b and a.startswith(family+':') for a,b in zip(gold,predicted))
scores[family]={'tp':tp,'fp':p-tp,'fn':g-tp,'f1':2*tp/(g+p) if g+p else 0.}
return {'families':scores,'macro_f1':sum(s['f1'] for s in scores.values())/len(scores),
'accuracy':sum(a==b for a,b in zip(gold,predicted))/len(gold) if gold else 0.,
'policy':'Two declared families, exact direction required, other excluded from the mean but its mistakes count; not the official SemEval scorer.'}
def assert_disjoint_groups(train,test):
overlap={group_key(r) for r in train}&{group_key(r) for r in test}
if overlap:raise ValueError('entity-pair leakage across split')
def example(a,b,words,reverse=False):
row={'tokens':[a,*words,b],'span1':[0,1],'span2':[len(words)+1,len(words)+2]}
if reverse:row['span1'],row['span2']=row['span2'],row['span1']
return {'e1':b if reverse else a,'e2':a if reverse else b,'sentences':[row]}
def demo():
train=[example('Ava','Birch',['works','for']),example('Cora','Delta',['works','for'],True),
example('Elm','Fjord',['is','in']),example('Grove','Harbor',['is','in'],True),
example('Ivy','Juniper',['met']),example('Kite','Larch',['met'])]
labels=list(LABELS[:4])+['other','other'];model=fit(train,labels)
test=[example('Mora','Nova',['works','for']),example('Opal','Pine',['is','in'],True),example('Quartz','Reed',['met'])]
assert_disjoint_groups(train,test);pred,prob=predict(model,test)
gold=['employment:e1-e2','location:e2-e1','other']
hand_gold=['employment:e1-e2','employment:e2-e1','location:e1-e2','other']
hand_pred=['employment:e2-e1','employment:e2-e1','other','location:e1-e2']
return {'training':train,'labels':labels,'test':test,'gold':gold,'predictions':pred,'probabilities':prob,
'vocabulary':model['vocabulary'],'loss_trace':model['loss_trace'],'test_metrics':metrics(gold,pred),
'direction_error':metrics(hand_gold,hand_pred),'other_inflation':metrics(hand_gold+['other']*20,hand_pred+['other']*20),
'scope':'Original lexical bag classifier with supplied entity IDs/spans and labels; synthetic test changes names, not templates. No knowledge-base alignment or semantic generalization claim.'}
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The training vocabulary is fitted once; unseen test features accumulate in a declaredUNK coordinate. The code does not add them to the vocabulary. Eighty deterministic line-search steps reduce mean training loss from1.609438 to0.016209. It uses no penalty and does not claim convergence, a finite maximum-likelihood optimum on separable data, or calibrated confidence.
Feature extraction rejects overlapping or invalid entity spans. Each bag has at most50 sentences of at most100 supplied tokens. A deliberate reversed-pair split is rejected. The code prints all probabilities, losses, vocabulary and metric counts, so the model’s behavior can be inspected without a pretrained encoder.
With a dense N×D feature matrix, linear scoring and a gradient pass cost O(NDK), plus feature extraction. Storing features, parameters and probabilities costs O(ND+DK+NK). Each accepted training step can require several objective evaluations; the line search caps trials at40. The fixed five-class example has no hierarchical output shortcut.
Direction and label balance change the evaluation
For a relation family f, count a true positive only if both family and direction match. Let G_f and P_f be the numbers of gold and predicted labels in that family. A reversed direction contributes bothFP andFN, even though its family is unchanged:
Average the per-family F1 values over this example’s two declared families. other has no term in the mean, but predicting it for a positive relation creates a false negative, and predicting a relation for a gold other creates a false positive.
SemEval-2010 Task8 uses a direction-aware macro score over its nine relations while excludingOTHER from the average. Our two-family function illustrates that distinction; it is not the official scorer. Averaging nineteen independent directional-label F1 scores is a different convention. Scoring specification, §3
In the printed error example, employment hasTP=1, FP=1, FN=1, so its F1 is1/2. Location has no correct prediction, so its F1 is0 and the family macro score is1/4. Adding twenty correctly classified other examples raises accuracy from1/4 to21/24 while leaving that macro score unchanged.
The schema permits only one label per pair bag. Multiple true relations, temporal changes and contradictory sentences require richer labels or a different aggregation model. Supplied entity spans also hide detection errors. Evaluate on distinct documents and entity groups with clearly stated annotation scope before making end-to-end claims.
Reverse, pool, calculate and audit
- Keep
Ava works for Birchbut swap e1 and e2. What must change in the features and label?
Answer: The argument-order features and the employment direction must reverse. Entity surface words remain excluded. A representation that discards this ordering cannot express the required distinction reliably.
- A bag contains two identical sentences. What happens to the feature vector, and why is this not twice the evidence from independent sources?
Answer: This program sums occurrences, so every feature count doubles. A copied sentence can be the same underlying observation; aggregation does not establish independence or truth. A different duplicate policy must be stated and evaluated.
- Employment hasTP1/FP1/FN1 and location hasTP0/FP1/FN1. Compute macroF1. Does adding twenty correct
otherrows improve it?
Answer: The family scores are1/2 and0, so macroF1=1/4. Extra correct other rows do not change either family count. In the four-row fixture, accuracy nevertheless rises from1/4 to21/24.
- A knowledge base contains an employment relation, but the observed sentence only says that the two entities met. May it be treated as a confirmed employment assertion?
Answer: No. It can supply a noisy distant label under an explicitly chosen training assumption, but the sentence does not itself express that relation. Keep sentence-level evidence, knowledge-base assertions and model predictions distinct; missing database entries also need an explicit negative-label policy.
A relation label only has meaning under its task definition
Mintz et al. show how an existing relation database can replace some direct annotation while introducing noisy supervision. SemEval’s task instead fixes marked arguments, a relation inventory and an evaluation protocol. These are different training and prediction units, so their reported scores cannot be substituted for one another. Distant supervision architecture Benchmark task
To extend the supplied lexical features, use contextual representations or paths from dependency parsing, retaining the same split and scoring contract. Joint entity/relation extraction must additionally measure entity boundaries and types. Information extraction then addresses how to preserve qualifiers and provenance when turning predictions into records.
Make a prediction, then check
A predicted employment relation has the correct family but reversed direction. How does this example score it?
Learning objectives
- Define relation direction, label scope and supplied-argument assumptions.
- Train a linear softmax classifier on direction-aware entity-pair features.
- Distinguish a sentence claim from knowledge-base distant supervision.
- Evaluate relation families with exact direction and group-safe splits.
Prerequisites & connections
Explore related knowledge →References
- Distant supervision for relation extraction without labeled data
Mike Mintz, Steven Bills, Rion Snow and Daniel Jurafsky · 2009 - SemEval-2010 Task8: Multi-Way Classification of Semantic Relations between Pairs of Nominals
Iris Hendrickx, Su Nam Kim, Zornitsa Kozareva, Preslav Nakov, Diarmuid Ó Séaghdha, Sebastian Padó, Marco Pennacchiotti, Lorenza Romano and Stan Szpakowicz · 2010
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-12 · Single AI author checked six paired equations and four explained exercises against scoped Mintz2009 and SemEval2010. Supplied directed entity pairs, order-sensitive lexical count bags, train-only vocabulary and full softmax gradients checked by25-parameter differences. Two-family direction-aware macro F1 excludes OTHER from the mean while preserving errors: twenty correct OTHER change accuracy1/4 to21/24 but macro stays1/4. Entity-pair split leakage checked. New-name tests reuse templates; no knowledge-base alignment, official nine-relation scorer or semantic generalization claim.
- Single AI author checked six paired equations and four explained exercises against scoped Mintz2009 and SemEval2010. Supplied directed entity pairs, order-sensitive lexical count bags, train-only vocabulary and full softmax gradients checked by25-parameter differences. Two-family direction-aware macro F1 excludes OTHER from the mean while preserving errors: twenty correct OTHER change accuracy1/4 to21/24 but macro stays1/4. Entity-pair split leakage checked. New-name tests reuse templates; no knowledge-base alignment, official nine-relation scorer or semantic generalization claim.
- Four original computed SVGs bind exact bilingual MDX. Eleven figure checks and36 isolated language/width cases with four fallback fonts passed; six actual desktop/mobile screenshots inspected by this AI author. This is separate from final full-page browser acceptance, with no human peer-review claim.
Source locations checked:
- Distant supervision for relation extraction without labeled data · Text175–240: directed binary relations, distant supervision, entity-pair feature aggregation, multiclass logistic regression and lexical features. Evaluation441–449 opening only; no complete benchmark or KB reproduction.
- SemEval-2010 Task8: Multi-Way Classification of Semantic Relations between Pairs of Nominals · Text19–66 inventory opening,94–114 annotation scope,170–177 supplied nominals; exact147–152 scoring excerpt: direction-aware nine-relation macroF1 excludingOTHER. Not full inventory details or scorer execution.
Related topics