AI Wiki中文/EN

Inductive logic programming: learning relational rules

归纳逻辑编程

Learn a two-edge relation from background facts and labeled examples, then test it on new entities.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A problem to solve

A graph contains edges a→b, b→c and c→d. Positive examples say that a relates to c and b relates to d; negative examples exclude direct and reversed connections. Instead of learning a weight for every named pair, can a system learn a reusable relation between edges?

Inductive logic programming, or ILP, learns logical rules using examples and background knowledge. Inference applies a rule that is already given; induction searches for the rule itself. A learned rule can then be applied to entities whose names never appeared in training. That reuse depends on the representation and hypothesis space, not on a promise that any few examples identify the intended rule. Inductive Logic Programming

Definitions and guarantees

Write BB for background knowledge, HH for a candidate program, and E+,E−E^+,E^- for positive and negative examples. In the noise-free learning-from-entailment setting used here, require:

B∪H⊨e(e∈E+),B\cup H\models e\quad(e\in E^+), B∪H⊭e(e∈E−).B\cup H\not\models e\quad(e\in E^-).

Not deriving a negative example is different from deriving its explicit negation. The finite example interprets listed background edges as the complete edge relation and computes ground consequences of one positive, nonrecursive rule. It does not implement every possible ILP semantics.

A candidate head is route2(X,Z). Its body contains one or two edge atoms over variables X, Y and Z; both head variables must occur in the body. For example:

route2(X,Z) :- edge(X,Y), edge(Y,Z)

A shared Y joins two edges. The resulting relation means a walk of exactly two edges; vertices need not be distinct. It is not unrestricted transitive reachability. A direct-edge rule and a reversed-edge rule belong to the search space too and can be excluded by examples.

The ILP survey describes background knowledge, meta-level search, recursion and predicate invention. Our one-rule language deliberately omits the latter two capabilities. It contains 28 syntactically distinct bodies after ignoring conjunction order, including repeated atoms. Some bodies may still be logically equivalent; syntax count is not semantic diversity. Inductive Logic Programming at30 — v2

A minimal implementation

The learner enumerates every allowed body and grounds its variables over the finite entities. It retains bodies that derive all positives and no negatives. The inner procedure reasons with a candidate; the outer loop learns by comparing candidates.

from itertools import product, combinations_with_replacement

def pairs(rows):
    result = set()
    for row in rows:
        if not isinstance(row, (tuple, list)) or len(row) != 2:
            raise ValueError("facts and examples must be pairs")
        if any(not isinstance(v, str) or not v for v in row):
            raise ValueError("entities must be nonempty strings")
        result.add(tuple(row))
    return frozenset(result)

def hypotheses():
    atoms = list(product(("X", "Y", "Z"), repeat=2))
    result = []
    for length in (1, 2):
        for body in combinations_with_replacement(atoms, length):
            variables = {v for atom in body for v in atom}
            if {"X", "Z"} <= variables:
                result.append(body)
    return result

def consequences(body, edges, entities):
    # Bodies come from hypotheses(); facts have been validated by pairs().
    variables = sorted({v for atom in body for v in atom})
    result = set()
    for values in product(entities, repeat=len(variables)):
        env = dict(zip(variables, values))
        if all((env[a], env[b]) in edges for a, b in body):
            result.add((env["X"], env["Z"]))
    return frozenset(result)

def learn(edge_rows, positive_rows, negative_rows):
    edges, positive, negative = map(pairs, (edge_rows, positive_rows, negative_rows))
    if positive & negative:
        raise ValueError("the same example cannot have opposite labels")
    entities = sorted({v for pair in edges | positive | negative for v in pair})
    if len(entities) > 8:
        raise ValueError("teaching limit: eight entities")
    accepted = []
    for body in hypotheses():
        predicted = consequences(body, edges, entities)
        if positive <= predicted and not (negative & predicted):
            accepted.append(body)
    return accepted

def show(body):
    return "route2(X,Z) :- " + ", ".join("edge("+a+","+b+")" for a,b in body)

if __name__ == "__main__":
    edges = [("a","b"), ("b","c"), ("c","d"), ("x","y")]
    positive = [("a","c"), ("b","d")]
    negative = [("a","b"), ("c","a"), ("a","d")]
    learned = learn(edges, positive, negative)
    print("hypotheses:", len(hypotheses()), "accepted:", len(learned))
    print(show(learned[0]))
    held_out = pairs([("p","q"), ("q","r"), ("r","s")])
    print("new graph:", sorted(consequences(learned[0], held_out, ("p","q","r","s"))))
    print("without labels:", len(learn(edges, [], [])))
hypotheses: 28 accepted: 1
route2(X,Z) :- edge(X,Y), edge(Y,Z)
new graph: [('p', 'r'), ('q', 's')]
without labels: 28

Exactly one body survives these labels. On a held-out chain p→q→r→s, it derives (p,r) and (q,s), showing that it uses relational structure rather than the original names. With no labels, all 28 bodies remain possible. That contrast makes the role of supervision visible.

For MM candidate bodies, cc entities, at most vv variables and bb body atoms, literal grounding takes O(Mcvb)O(Mc^v b) time, plus output-set operations. Here v≤3v\le3, b≤2b\le2 and the learner rejects more than eight entities. Indexed joins can be much more efficient on sparse relations, but are not needed to understand this reference implementation.

The helper consequences accepts bodies produced by hypotheses and validated facts; it is not a general parser or Prolog engine. Entity renaming changes displayed names but not which relational pattern the learned body expresses.

Limits and alternatives

Consistency on training examples is not generalization. The intended concept may lie outside the chosen language, several bodies may fit equally well, and mislabeled data may make every body fail. Returning no candidate means no body in this finite space meets these exact constraints, not that no logical explanation exists.

Background knowledge is also work. Turning images, text or sensor data into reliable ground facts can be harder than the small rule search shown here. The ILP survey explicitly discusses noisy observations and the difficulty of obtaining symbolic input; readable rule syntax does not automatically guarantee faithful explanation of an uncertain world. Inductive Logic Programming at30 — v2

Broader ILP systems may learn multiple clauses, recursive programs or new predicates. Those features increase expressiveness and change the search and evaluation problem. Keep the learned program, background theory, examples and language bias together when reporting a result.

Exercises with answers

1. Why does the shared variable Y matter?

It requires the end of the first edge to be the start of the second.

2. Does the learned rule derive a relation from p to s in the held-out chain?

No. That requires three edges, while this rule joins exactly two.

3. What does learning return without any positive or negative labels?

All 28 allowed bodies, because none is excluded by labels.

4. Is not deriving a negative example the same as proving its negation?

No. The coverage condition tests absence of entailment in the chosen setting.

Research and next steps

Read Muggleton for the logic-and-learning motivation and the later survey for background knowledge, search and limitations. Compare the example’s restricted hypothesis language with the richer systems rather than treating its small runtime as a general ILP performance result.

Continue with first-order logic, forward chaining and program synthesis.

Make a prediction, then check

How many candidate bodies survive with no labels?

Choose one answer

Learning objectives

  • Distinguish applying a logical rule from learning its body.
  • Check coverage, ambiguity and transfer under an explicit hypothesis language.

Prerequisites & connections

Explore related knowledge →

References

  1. Inductive Logic Programming
    Stephen Muggleton · 1991
  2. Inductive Logic Programming at30 — v2
    Andrew Cropper; Sebastijan Dumančić; Richard Evans; Stephen H. Muggleton · 2021

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit finite models, executed programs, independent mathematical/exhaustive references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.

  • Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
  • Verified7 tests:28 bodies/one learned join, all512 three-node directed graphs against independent two-edge composition, renamed and held-out entities, absent background, conflicting labels and malformed facts.
  • Compared both locale arguments, definitions, assumptions, formulas, code, results and all four exercises. Original finite teaching programs; no published system or research benchmark reproduction claimed. Catalogue IDs corrected before freezing.
  • Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • Inductive Logic Programming · Abstract/introduction and physical2–4 discussion of relational representation and background knowledge; no commercial ranking adopted.
  • Inductive Logic Programming at30 — v2 · v2 physical1–4 intro/meta-level positive/negative coverage; selected11/18 noisy observations and symbolic-input limits.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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