AI Wiki中文/EN

Information extraction: keep meaning attached to the record

信息抽取

Define a schema, preserve qualifiers and provenance, run an auditable baseline, and evaluate complete records.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A useful row must remember what the sentence actually said

Suppose a system collects acquisition statements from documents. Aster Labs acquired Beacon Works and Aster Labs did not acquire Beacon Works contain the same companies and relation verb. A table that keeps only those three items turns incompatible statements into the same row.

Information extraction, IE, converts selected information in text into structured records. The selected schema matters: a list of names, a relation table and an event record answer different questions. The NLTK book introduces extraction through specified entity relations and a pipeline from document processing to entity and relation detection. Scope and architecture, §§1–1.1

Our task is deliberately narrow: extract dated acquisition statements involving a supplied list of organizations. Retain the source document, exact text interval, subject, object, date, polarity, modality and attribution. These are statements found in documents, not independently verified transactions. The invented examples below require no private data or outside service.

The same acquisition tuple can carry a denial, a possibility or a quoted source. Keeping these qualifiers changes complete-record F1 from 4/11 to 10/11 on seven invented documents.
The same acquisition tuple can carry a denial, a possibility or a quoted source. Keeping these qualifiers changes complete-record F1 from 4/11 to 10/11 on seven invented documents.

Agree on the schema before selecting a model

Define one record and its boundaries

The record’s predicate is the canonical value acquire. polarity is positive or negative; modality is asserted or possible. attribution preserves a named source in an According to … prefix. The original subject/object/date surfaces and their half-open character intervals remain attached. A document ID plus sentence interval identifies an occurrence; it is not an entity identifier.

Two dates can describe different events, and two sources can make contradictory statements about one event. Grouping by subject, predicate, object and date should collect the evidence, not overwrite the earlier row. This example flags opposing asserted polarities and always leaves verified_real_world_fact false.

Name normalization only folds case, Unicode compatibility forms and whitespace. It does not establish that Aster and Aster Labs name the same company. A separate entity-linking decision would require evidence. The supplied registry bounds this baseline’s names; unknown entities are sent to review rather than guessed.

A baseline exposes the task’s hidden assumptions

Start with manual transcription of a small sample and a rules baseline. Here one supported statement occupies one line. Organization names use a bounded ASCII pattern, a date must be a valid ISO calendar date, and the allowed verb forms are acquired, did not acquire and may acquire. Other syntax is explicitly rejected.

This restriction is useful for comparison: it reveals unsupported coverage and qualifier errors before a larger model is introduced. It is not a claim that document language follows this grammar. A learned extractor can propose richer candidates later, but should be evaluated under the same declared record schema and source checks.

Pipeline quality compounds. If E, R and Q mean correct entities, relation and qualifiers, the chain rule gives the probability of a completely correct result:

P(E∩R∩Q)=P(E)P(R∣E)P(Q∣E∩R).P(E\cap R\cap Q)=P(E)P(R\mid E)P(Q\mid E\cap R).

Three conditional rates of0.9 give0.729. Multiplying three unrelated headline accuracies would not justify that number. Measuring only the final relation classifier on gold entities hides earlier failures.

Preserve consequential context

Negation, possibility and attribution change what a record asserts. Shortening text can also remove essential meaning: Angeli et al. discuss constraints on clause shortening, including why a non-subsective adjective such as fake cannot simply disappear from fake gun. Their system combines clause splitting and natural-logic-based shortening before forming triples. Our program uses a small explicit grammar, not that algorithm. Introduction and intra-clause discussion

Structured syntax checks answer whether a record has the required shape. Source-span checks answer whether its text fields occur at the stated locations. Neither independently proves that the original author was correct.

Run a complete, auditable rules baseline

The block uses only the Python3.12 standard library. Save it as one file and run it. Seven invented documents include positive, negative, possible and attributed claims, an invalid date, and a valid passive sentence outside the grammar. The entity registry is supplied explicitly. No language model, entity detector or database is downloaded.

"""Original, deliberately narrow acquisition-record extraction baseline."""
import datetime,hashlib,json,re,unicodedata

NAME=r'[A-Z][A-Za-z0-9&-]*(?: [A-Z][A-Za-z0-9&-]*){0,3}'
PATTERN=re.compile(rf'(?:(?:According to) (?P<source>{NAME}), )?(?P<subject>{NAME}) (?P<verb>acquired|did not acquire|may acquire) (?P<object>{NAME}) on (?P<date>\d{{4}}-\d{{2}}-\d{{2}})\.')


def normalized(name):
    return ' '.join(unicodedata.normalize('NFKC',name).split()).casefold()


def extract(documents, entities):
    if not isinstance(entities,(list,tuple,set)) or not entities or any(not isinstance(e,str) or not e.strip() for e in entities):
        raise ValueError('explicit nonempty entity registry required')
    registry={normalized(e) for e in entities}
    if len(registry)!=len(entities):raise ValueError('ambiguous duplicate registry names')
    claims=[];rejected=[];seen=set()
    for doc in documents:
        if not isinstance(doc,dict) or not isinstance(doc.get('id'),str) or not doc['id'] or not isinstance(doc.get('text'),str):
            raise ValueError('each document needs nonempty id and string text')
        if doc['id'] in seen or len(doc['text'])>50000:raise ValueError('duplicate document id or document too long')
        seen.add(doc['id']);offset=0
        for raw in doc['text'].splitlines(keepends=True):
            line=raw.strip();start=offset+len(raw)-len(raw.lstrip());end=start+len(line);offset+=len(raw)
            if not line:continue
            match=PATTERN.fullmatch(line) if len(line)<=1000 else None
            reason='unsupported grammar' if match is None else None
            if match:
                try:datetime.date.fromisoformat(match['date'])
                except ValueError:reason='invalid date'
            if match and not reason and any(normalized(match[k]) not in registry for k in ['subject','object']):
                reason='unknown entity'
            if reason:
                rejected.append({'document':doc['id'],'span':[start,end],'text':line,'reason':reason});continue
            fields={}
            for name in ['subject','object','date']:
                a,b=match.span(name);fields[name]={'surface':match[name],'span':[start+a,start+b]}
                assert doc['text'][start+a:start+b]==match[name]
            key=f'{doc["id"]}\0{start}\0{end}'
            claims.append({'id':hashlib.sha256(key.encode()).hexdigest(),'document':doc['id'],'span':[start,end],
                'text':line,'predicate':'acquire','subject':normalized(match['subject']),'object':normalized(match['object']),
                'date':match['date'],'polarity':'negative' if match['verb']=='did not acquire' else 'positive',
                'modality':'possible' if match['verb']=='may acquire' else 'asserted',
                'attribution':match['source'],'fields':fields,'rule':'acquisition-v1'})
    return {'claims':claims,'rejected':rejected}


def assertion_key(record):
    return (record['document'],tuple(record['span']),record['subject'],record['predicate'],record['object'],
            record['date'],record['polarity'],record['modality'],record['attribution'])


def evaluate(predicted,gold):
    p,g=set(map(assertion_key,predicted)),set(map(assertion_key,gold));tp=len(p&g);fp=len(p-g);fn=len(g-p)
    return {'tp':tp,'fp':fp,'fn':fn,'precision':tp/len(p) if p else 0.,'recall':tp/len(g) if g else 0.,
            'f1':2*tp/(2*tp+fp+fn) if p or g else 0.,'unit':'complete assertion with document/sentence span; duplicate keys count once'}


def aggregate(claims):
    groups={}
    for c in claims:
        key=tuple(c[k] for k in ['subject','predicate','object','date']);groups.setdefault(key,[]).append(c)
    result=[]
    for key,evidence in sorted(groups.items()):
        polarities={c['polarity'] for c in evidence if c['modality']=='asserted'}
        result.append({'tuple':list(key),'evidence':[{'id':c['id'],'document':c['document'],'span':c['span'],
            'polarity':c['polarity'],'modality':c['modality'],'attribution':c['attribution']} for c in evidence],
            'opposing_assertions':polarities=={'positive','negative'},'verified_real_world_fact':False})
    return result


def demo():
    texts=['Aster Labs acquired Beacon Works on 2024-03-04.',
           'Aster Labs did not acquire Beacon Works on 2024-03-04.',
           'Harbor Group may acquire Delta Labs on 2025-01-02.',
           'According to Cedar News, Elm Corp acquired Fern Labs on 2023-11-20.',
           'Grove Corp acquired Hill Labs on 2025-02-30.',
           'Pine acquired Oak on 2024-05-06.',
           'Ivy Corp was acquired by Juniper Labs on 2024-06-07.']
    docs=[{'id':f'd{i}','text':text} for i,text in enumerate(texts)]
    entities=['Aster Labs','Beacon Works','Harbor Group','Delta Labs','Elm Corp','Fern Labs','Grove Corp','Hill Labs','Pine','Oak','Ivy Corp','Juniper Labs']
    parsed=extract(docs,entities)
    # Manual schema labels; the final passive sentence is deliberately unsupported.
    rows=[('aster labs','beacon works','2024-03-04','positive','asserted',None,0),
          ('aster labs','beacon works','2024-03-04','negative','asserted',None,1),
          ('harbor group','delta labs','2025-01-02','positive','possible',None,2),
          ('elm corp','fern labs','2023-11-20','positive','asserted','Cedar News',3),
          ('pine','oak','2024-05-06','positive','asserted',None,5),
          ('juniper labs','ivy corp','2024-06-07','positive','asserted',None,6)]
    gold=[{'document':f'd{i}','span':[0,len(texts[i])],'subject':s,'predicate':'acquire','object':o,'date':date,
           'polarity':polarity,'modality':modality,'attribution':source} for s,o,date,polarity,modality,source,i in rows]
    stripped=[dict(c,polarity='positive',modality='asserted',attribution=None) for c in parsed['claims']]
    return {'documents':docs,'entities':entities,'extraction':parsed,'gold':gold,'qualified_score':evaluate(parsed['claims'],gold),
            'context_stripped_score':evaluate(stripped,gold),'groups':aggregate(parsed['claims']),
            'scope':'Original case-sensitive ASCII-name line grammar with supplied entity registry; no automatic language model, entity linking or verification of real-world truth.'}

if __name__=='__main__':print(json.dumps(demo(),indent=2,ensure_ascii=False))

Five records are extracted. The impossible date is rejected; the unsupported passive sentence is also visible in the rejection list. Every accepted sentence and subject/object/date field points to its exact substring in the input. Indentation, blank lines and CRLF endings are covered by the checks.

A meaningful failure occurred during development: without an entity registry, the initial capitalization pattern accepted If A as a company in If A acquired B on 2024-01-01.. Requiring known entities prevents that error in the controlled task and makes unknown names explicit. It does not constitute general conditional-sentence understanding. The original failing version is retained in the repository’s preflight evidence.

The gold fixture is explicitly enumerated and includes the unsupported passive statement with its subject/object order reversed correctly. Compare complete occurrence records, including qualifiers and source interval. The qualified baseline hasTP=5, FP=0, FN=1. A deliberately damaged comparison strips polarity, modality and attribution from the same candidates and hasTP=2, FP=3, FN=4.

P=TPTP+FP,R=TPTP+FN,F1=2TP2TP+FP+FN.P=\frac{TP}{TP+FP},\qquad R=\frac{TP}{TP+FN},\qquad F_1=\frac{2TP}{2TP+FP+FN}.

Their F1 values are10/11 and4/11. These are exact results on this small fixture, not estimates of deployed performance. Duplicate occurrence keys count once; all-zero denominators map to0. Record-level evaluation prevents correct-looking names from masking wrong qualifiers.

Plan for rejection, disagreement and cost

The code caps each document at50,000 characters and each candidate line at1,000. Its bounded grammar and dictionary lookups keep the scan small; groupingG distinct tuples additionally sorts them in O(G log G) comparisons. Name and text lengths contribute their own processing cost. This does not characterize the cost of an unrestricted learned system.

The registry prevents free-form name invention but limits coverage. The grammar misses many valid passives, abbreviations, nested clauses, multilingual names and cross-sentence relations. A strict baseline should make those omissions measurable. Expanding a pattern without expanding adversarial examples can improve apparent recall while silently changing meaning.

For a larger system, compare rule-only extraction, a supervised span/relation model, and model-proposed records checked against sources. Measure each on the same held-out documents. Split by source or time where near-duplicate documents would otherwise leak across sets; keep document revisions and entity mappings versioned. Valid JSON is only the entry condition.

Choose review thresholds using the consequences of wrong and missing records. One simple accounting model is:

C=cFPFP+cFNFN+creviewNreview.C=c_{FP}FP+c_{FN}FN+c_{review}N_{review}.

The coefficients are per-case costs under a declared application policy, not universal constants. Record abstention rate, review time and the kinds of errors reviewers repair. Preserve contradictory evidence for resolution; do not convert a majority vote among copied sources into independent verification.

Keep meaning attached to the fields

  1. May a possible acquisition be stored as a completed transaction if both company names and the date are correct?

Answer: No. The event’s modality is part of this schema. Correct entities and dates cannot compensate for changing possibility into an assertion of completion. The record must preserve possible and its source.

  1. Compute the two F1 values from the fixture’s counts. What does removing qualifiers change?

Answer: The qualified baseline gives10/(10+0+1)=10/11. The damaged comparison gives4/(4+3+4)=4/11. It changes the meaning of three otherwise recognizable records; it does not improve coverage.

  1. Two documents contain identical statements; a third denies the same subject/predicate/object/date tuple. What should aggregation retain?

Answer: Keep each occurrence’s document and source interval, collect all three evidence items and flag opposing asserted polarities. Deduplicating the tuple must not erase provenance or disagreement. Repeated text is not necessarily independent evidence.

  1. A new pattern handles the passive sentence. Is a higher fixture recall enough to approve the change?

Answer: No. Add tests for subject/object direction, negation, possibility, attribution and exact offsets. Recheck complete-record precision and rejection behavior on unseen examples. The fixture is a development check, not a sealed test set once it has guided the rule change.

Extraction scope determines what counts as success

The NLTK architecture is a useful decomposition of entity and relation processing. Angeli et al.‘s2015 OpenIE work illustrates a different choice: extracting relation phrases without fixing one closed relation inventory, while preserving semantic constraints during clause shortening. A production schema may later map such open phrases to fixed fields. This article did not reproduce their training or full pattern collection. Pipeline organization OpenIE approach

Named entity recognition studies typed mention boundaries. Relation extraction concerns relations between selected arguments; coreference groups identity mentions across occurrences. Model evaluation provides the wider discipline for choosing splits, baselines and acceptance criteria. Keep their error sources visible when combining them.

Make a prediction, then check

The source says that Harbor Group may acquire Delta Labs. Which record preserves its meaning?

Choose one answer

Learning objectives

  • Define a record schema and the statements it is allowed to represent.
  • Preserve negation, modality, attribution and exact source offsets.
  • Build a reproducible rules baseline with explicit abstention.
  • Evaluate complete records and trace upstream error costs.

Prerequisites & connections

Explore related knowledge →

References

  1. NLTK Book, Chapter7: Extracting Information from Text
    Steven Bird, Ewan Klein and Edward Loper
  2. Leveraging Linguistic Structure For Open Domain Information Extraction
    Gabor Angeli, Melvin Jose Johnson Premkumar and Christopher D. Manning · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-12 · Single AI author checked the engineering workflow, three paired equations and four explained exercises against scoped NLTK pipeline and Angeli clause/context passages. Controlled grammar with explicit entity registry preserves document/field offsets, dates, negation, modality, attribution, rejection reasons and conflicting source records. Seven synthetic documents yield qualified F1=10/11 versus stripped4/11; counts5/0/1 versus2/3/4 checked. Initial conditional misparse and corrected registry requirement retained. No entity linking, real-world truth verification or business performance claim.

  • Single AI author checked the engineering workflow, three paired equations and four explained exercises against scoped NLTK pipeline and Angeli clause/context passages. Controlled grammar with explicit entity registry preserves document/field offsets, dates, negation, modality, attribution, rejection reasons and conflicting source records. Seven synthetic documents yield qualified F1=10/11 versus stripped4/11; counts5/0/1 versus2/3/4 checked. Initial conditional misparse and corrected registry requirement retained. No entity linking, real-world truth verification or business performance 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.