mixle.stats.graphs.knowledge_graph module¶
Knowledge-graph embedding distributions for integer triple observations.
Data type: a triple (h, r, t) of integer indices – head entity, relation, tail entity. The model
embeds each entity and relation in dim dimensions and scores a triple by the DistMult bilinear form
score(h, r, t) = sum_k E[h, k] * R[r, k] * E[t, k] = (E[h] * R[r]) . E[t],
and defines the conditional tail distribution by a softmax over all entities,
p(t | h, r) = softmax_t score(h, r, t).
The modeled joint law uses explicit uniform context laws,
p(h,r,t)=p(h)p(r)p(t|h,r). The sampler and log_density therefore
describe the same normalized random variable; tail/head/relation posterior
helpers remain conditional query APIs. Maximizing the joint law is equivalent
to maximizing its tail-conditional term because the context factors are
fixed.
It has no closed form, so – exactly like the Plackett-Luce minorization-maximization estimator in this
package – each fit / optimize iteration performs one full-batch gradient-ascent step on the
embeddings, evaluated at the previous estimate (a random seeded init seeds the first pass). The threaded
estimate carries the embeddings between passes, so no parameter state lives outside the framework.
- class KnowledgeGraphStatistics(count, triples, weights, num_entities, num_relations, dim, warm_entity, warm_relation)[source]
Bases:
NamedTupleVersioned weighted triples plus an optional immutable warm start.
- Parameters:
- count: float
Alias for field number 0
- triples: ndarray
Alias for field number 1
- weights: ndarray
Alias for field number 2
- num_entities: int
Alias for field number 3
- num_relations: int
Alias for field number 4
- dim: int
Alias for field number 5
- property schema_version: int
Return the serialized-statistic schema version.
- class KnowledgeGraphDistribution(entity_embeddings, relation_embeddings, name=None, keys=None, fit_receipt=None)[source]
Bases:
SequenceEncodableProbabilityDistributionDistMult knowledge-graph embedding distribution over triples
(h, r, t).entity_embeddingsis(num_entities, dim)andrelation_embeddingsis(num_relations, dim).log_density((h, r, t))is the conditional tail log-probabilitylog p(t | h, r)under the entity softmax.- Parameters:
- score(h, r, t)[source]
DistMult score of a single triple (higher is more plausible).
- tail_log_posterior(h, r)[source]
Length-
num_entitiesvector oflog p(t | h, r)over all tail candidates.
- head_log_posterior(r, t)[source]
Length-
num_entitiesvector oflog p(h | r, t)over all head candidates.
- relation_log_posterior(h, t)[source]
Length-
num_relationsvector oflog p(r | h, t)over all relation candidates.
- complete(h=None, r=None, t=None)[source]
Log-posterior over candidates for the single missing slot of a query.
Exactly one of
h,r,tmust beNone; the returned vector is over entities (for a missing head or tail) or relations (for a missing relation).
- rank(h=None, r=None, t=None, exclude=(), top_n=None)[source]
Rank candidates for the missing slot by log-probability, dropping
excludecandidates.Returns
[(candidate, log_prob), ...]highest first (the most plausible completions).
- recommend(known, top_n=10)[source]
Recommend the most plausible missing tail facts for the
(h, r)contexts inknown.knownis a sequence of observed(h, r, t)triples; for each distinct(h, r)the already-present tails are excluded, the remaining tails are ranked bylog p(t | h, r), and the global toptop_nnew facts are returned as[(h, r, t, log_prob), ...].
- recommend_subgraph(node, known, top_n=5)[source]
Recommend plausible new edges incident to
node(both(node, r, ?)and(?, r, node)).Excludes edges already in
knownand returns the toptop_nby log-probability as[(h, r, t, log_prob), ...], the suggested missing subgraph around the node.
- pattern(pattern, candidates=None, known=None, beam=64)[source]
A subgraph-pattern query over this model for flexible enumeration of missing parts.
patternis a list of triples whose slots are either fixed integer ids or named variables (strings starting with'?'), variables shared across edges (e.g.[(alice, friend, '?x'), ('?x', lives_in, '?c')]). The returnedKnowledgeGraphPatternenumerates the variable bindings (completed subgraphs) in descending joint plausibility, restricts variables tocandidatesif given, drops groundings that add nothing new whenknownis given, and plugs intoConformalStructurefor a calibrated set of completed subgraphs.
- log_density(x)[source]
Return normalized joint
log p(h,r,t)for one triple.
- seq_log_density(x)[source]
Return vectorized tail log-probabilities for encoded triples.
- sampler(seed=None)[source]
Return a sampler for observed triples.
- Parameters:
seed (int | None)
- Return type:
KnowledgeGraphSampler
- estimator(pseudo_count=None)[source]
Return a DistMult embedding estimator for this entity/relation shape.
- Parameters:
pseudo_count (float | None)
- Return type:
KnowledgeGraphEstimator
- dist_to_encoder()[source]
Return the triple encoder used by vectorized methods.
- Return type:
KnowledgeGraphDataEncoder
- class KnowledgeGraphSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw triples: head and relation uniformly, tail from the conditional softmax
p(t | h, r).- Parameters:
dist (KnowledgeGraphDistribution)
seed (int | None)
- class KnowledgeGraphAccumulator(num_entities, num_relations, dim, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorCollect the observed triples (and weights) for the estimator to train on.
A DistMult embedding model has no finite sufficient statistic, so – like other non-exponential-family models in this package – the accumulator retains the data: it concatenates the
(h, r, t)triples seen across the (possibly distributed) partitions. The estimator then runs the gradient training inKnowledgeGraphEstimator.estimate().- update(x, weight, estimate)[source]
Store one weighted triple for embedding training.
- initialize(x, weight, rng)[source]
Store one weighted triple during initialization.
- Parameters:
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_initialize(x, weights, rng)[source]
Store encoded triples during initialization.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Store encoded triples and weights for embedding training.
- combine(suff_stat)[source]
Merge stored triples and weights from another accumulator value.
- Parameters:
suff_stat (Any)
- Return type:
KnowledgeGraphAccumulator
- value()[source]
Return total weight, stacked triples, and stacked weights.
- Return type:
KnowledgeGraphStatistics
- from_value(x)[source]
Restore stored triples and weights from
valueoutput.- Parameters:
x (Any)
- Return type:
KnowledgeGraphAccumulator
- scale(c)[source]
Scale the observation weights without changing triples or warm start.
- Parameters:
c (float)
- Return type:
KnowledgeGraphAccumulator
- key_merge(stats_dict)[source]
Merge evidence under the configured shared key.
- key_replace(stats_dict)[source]
Replace evidence from the configured shared key.
- acc_to_encoder()[source]
Return the encoder compatible with stored triples.
- Return type:
KnowledgeGraphDataEncoder
- class KnowledgeGraphAccumulatorFactory(num_entities, num_relations, dim, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for KnowledgeGraphAccumulator.
- make()[source]
Create an empty knowledge-graph accumulator.
- Return type:
KnowledgeGraphAccumulator
- class KnowledgeGraphEstimator(num_entities, num_relations, dim=16, lr=0.5, epochs=100, batch_size=256, weight_decay=0.0, init_scale=0.3, max_norm=1.0, directions=('tail',), negatives=None, seed=1, pseudo_count=None, name=None, keys=None, objective=None, initial_model=None)[source]
Bases:
ParameterEstimatorTrain DistMult knowledge-graph embeddings by maximizing the tail-softmax log-likelihood.
estimateruns vectorized mini-batch gradient ascent (epochspasses, batch sizebatch_size, steplrwith L2weight_decay) from a deterministic seeded init, projecting each entity embedding back to the unit ball every epoch so the scale – hence the step size – stays well behaved. Oneoptimize/fititeration (max_its=1) trains the model; the data is supplied through the accumulator like any other estimator.- Parameters:
num_entities (int)
num_relations (int)
dim (int)
lr (float)
epochs (int)
batch_size (int)
weight_decay (float)
init_scale (float)
max_norm (float)
directions (tuple)
negatives (int | None)
seed (int)
pseudo_count (float | None)
name (str | None)
keys (str | None)
objective (str | None)
initial_model (KnowledgeGraphDistribution | None)
- accumulator_factory()[source]
Return a factory for stored-triple accumulators.
- Return type:
KnowledgeGraphAccumulatorFactory
- class KnowledgeGraphDataEncoder(num_entities, num_relations)[source]
Bases:
DataSequenceEncoderEncode a sequence of
(h, r, t)triples into an(N, 3)integer array.- seq_encode(x)[source]
Validate and encode triples as an
(N, 3)integer array.
- class KnowledgeGraphEnsemble(members)[source]
Bases:
objectAn ensemble of independently fit
KnowledgeGraphDistributionmodels, for epistemic (model) uncertainty over completions.The members share the entity and relation index spaces but are fit from different random seeds, so where the data pins the answer down they agree and where it does not they disagree. The mean tail posterior averages
p(t | h, r)across members; the epistemic uncertainty is the mutual information (BALD)H(mean) - mean_m H(member_m)– the part of the predictive entropy that comes from disagreement among members rather than from genuine ambiguity.- Parameters:
members (list[KnowledgeGraphDistribution])
- mean_tail_posterior(h, r)[source]
The ensemble-averaged
p(t | h, r)over all tail candidates.
- epistemic_tail_uncertainty(h, r)[source]
Mutual-information (BALD) epistemic uncertainty of the tail completion (nats); 0 if members agree.
Thin wrapper over the general
mixle.inference.uncertainty.decompose_entropy()– the tail posteriorsp(t | h, r)per member are exactly the categorical predictives it splits.
- fit_knowledge_graph_ensemble(triples, num_entities, num_relations, dim=16, members=5, bootstrap=False, rng=None, **estimator_kwargs)[source]
Fit
membersknowledge-graph models and wrap them in an ensemble.Members differ by their random seed; with
bootstrap=Trueeach is also fit on a bootstrap resample of the triples (bagging), which spreads the members further apart where the data is thin and so sharpens the epistemic-uncertainty estimate.
- class KnowledgeGraphPattern(kg, pattern, candidates=None, known=None, beam=64)[source]
Bases:
objectA subgraph-pattern query over a fitted
KnowledgeGraphDistribution.A pattern is a list of triples whose slots are fixed integer ids or named variables (strings starting with
'?'); a variable may recur across edges (shared join), and a variable in the relation slot ranges over relations, otherwise over entities. A binding assigns every variable a value. Edgewise conditional factors define an unnormalized binding potential; this class computes the finite binding-space partition function andlog_densityreturns the normalized probability over bindings.enumeratereturns the most plausible completed subgraphs, andenumeratoryields them lazily in descending score (a best-first beam of widthbeam), so the object also satisfies the structure-distribution interface (log_density+enumerator) and can be handed toConformalStructurefor a calibrated set of completed subgraphs. A binding is represented as a tuple of values in the canonical (sorted) variable order;binding()builds one from a dict andtriples()grounds it to edges.- binding(assignment)[source]
Canonical binding tuple (sorted-variable order) from a
{variable: value}dict.
- triples(binding)[source]
Ground a binding tuple to the list of completed
(h, r, t)edges.
- log_density(binding)[source]
Normalized log-probability of a complete binding.
- enumerator()[source]
Yield
(binding, joint_log_prob)over completed subgraphs in descending score (beam-limited).