API Documentation

embeddings

class deepproblog.embeddings.Embedding(n: int, block_size: int = 32, renormalize: bool = False)[source]

Bases: TermEmbedder

Embeds terms with learnable embeddings. The memory for the embeddings is allocated in blocks.

get_all_embeddings(n: int | None = None) → Tensor[source]
Parameters:

n – Optional int. Limits the returned embeddings to the first n.

Returns:

A tensor containing the embeddings.

get_embedding(term)[source]
Parameters:

term – Term to be embedded

Returns:

get_embeddings_by_label(labels: Collection[Term]) → Tensor[source]
Parameters:

labels – A list of terms.

Returns:

Returns the tensor of the embeddings of the terms in label in order.

parameters() → List[Parameter][source]
Returns:

A list of all parameters of the embeddings.

step()[source]

Perform calls the step method for the optimizers of the contained learned embeddings.

zero_grad()[source]

Zeroes the gradients for the learnable tensors.

class deepproblog.embeddings.OneHotEncoding(n: int)[source]

Bases: TermEmbedder

One-hot embedder. Assign each unique term a unique one-hot embedding.

get_embedding(term)[source]
Parameters:

term – Term to be embedded

Returns:

class deepproblog.embeddings.TermEmbedder[source]

Bases: ABC

Generic embedder for terms.

abstract get_embedding(term: Term) → Tensor[source]
Parameters:

term – Term to be embedded

Returns:

step()[source]

Perform calls the step method for the optimizers of the contained learned embeddings.

zero_grad()[source]

Zeroes the gradients for the learnable tensors.

tensor

class deepproblog.tensor.TensorStore[source]

Bases: object

A class that allows tensor to be stored and associated with a unique identifier.

clear()[source]

Clear the tensor store. :return:

store(tensor: Tensor, i: int | Term | None = None) → int | Term[source]

Stores a tensor. :param tensor: The tensor to store. :param i: If given, then tensor will be stored with index i, otherwise, a unique integer will be used. :return: The unique identifier of the stored tensor.

query

class deepproblog.query.Query(query: Term, substitution: dict | None = None, p: float = 1.0, output_ind: Sequence[int] = (-1,))[source]

Bases: object

The query object.

output_values() → List[Term][source]
Returns:

The values of the output arguments

replace_output(new_values: List[Term]) → Query[source]

Replaces the output variables :param new_values: The new values in order that should replace the output variables. :return: The query with the out_variables replaced by the corresponding new values.

substitute(substitution: dict | None = None) → Query[source]
Parameters:

substitution – The dictionary that will be used to perform the substitution. If None, then self.substitution will be used instead.

Returns:

A new query where the substitution is applied. See the apply_term method from the Term class for details on the substitution.

to_text_query()[source]

Return the query on a form where QueryDataset can load it

variable_output() → Query[source]
Returns:

A new query identical to the current one, but with the output arguments replaced with variables.

dataset

class deepproblog.dataset.Dataset[source]

Bases: ABC

fold(n: int, i: int) → Tuple[Dataset, Dataset][source]
Parameters:
  • n – The number of folds to make.

  • i – Which of the folds is the held-out set.

Returns:

A tuple of the training fold and test fold datasets.

subset(i: int, j: int | None = None) → Dataset[source]
Parameters:
  • i – index i

  • j – index j

Returns:

If j is None, returns a subset with the indices [0,i], else returns a subset with the indices [i, j]

to_file_repr(i: int) → str[source]
Parameters:

i – index

Returns:

Returns a string representation of file i suitable for writing to a file. Defaults to to_query.

to_queries() → List[Query][source]
Returns:

A list of all queries in the dataset.

abstract to_query(i: int) → Query[source]
Parameters:

i – Index i

Returns:

The i-th example as a Query object

write_to_file(f: TextIO)[source]
Parameters:

f – File to write the dataset. to

class deepproblog.dataset.Extension(a, b)[source]

Bases: Dataset

to_file_repr(i)[source]
Parameters:

i – index

Returns:

Returns a string representation of file i suitable for writing to a file. Defaults to to_query.

to_query(i, *args)[source]
Parameters:

i – Index i

Returns:

The i-th example as a Query object

class deepproblog.dataset.Fold(parent, n, i, split)[source]

Bases: Dataset

to_file_repr(i)[source]
Parameters:

i – index

Returns:

Returns a string representation of file i suitable for writing to a file. Defaults to to_query.

to_query(i)[source]
Parameters:

i – Index i

Returns:

The i-th example as a Query object

class deepproblog.dataset.ImageDataset(root, extension='png', transform=None)[source]

Bases: Dataset, ABC

class deepproblog.dataset.MutatingDataset(inner_dataset: Dataset, mutator: Callable[[int, Query], Query])[source]

Bases: Dataset

Generic dataset adapter that mutates an underlying dataset.

Intended use cases involve generating noisy datasets as well as negative examples.

to_query(i: int) → Query[source]
Parameters:

i – Index i

Returns:

The i-th example as a Query object

class deepproblog.dataset.NoiseMutatorDecorator(p: float, inner_mutator: Callable[[int, Query], Query], seed: int | None = None)[source]

Bases: object

Dataset mutator that will mutate with a certain probability

class deepproblog.dataset.NumericIncorrectOutputMutator(domain: List[int], change_p=False, seed: int | None = None)[source]

Bases: object

Dataset mutator that replaces numeric output with an incorrect value. Only constants are supported.

class deepproblog.dataset.QueryDataset(queries: List[Query] | Path | str)[source]

Bases: Dataset

Dataset that loads queries from a file or a list

to_query(i)[source]
Parameters:

i – Index i

Returns:

The i-th example as a Query object

class deepproblog.dataset.Subset(dataset, i, j)[source]

Bases: Dataset

to_file_repr(i)[source]
Parameters:

i – index

Returns:

Returns a string representation of file i suitable for writing to a file. Defaults to to_query.

to_query(i, *args)[source]
Parameters:

i – Index i

Returns:

The i-th example as a Query object

network

class deepproblog.network.Network(network_module: Module, name: str, optimizer: Optimizer | None = None, scheduler=None, k: int | None = None, batching: bool = False)[source]

Bases: object

Wraps a PyTorch neural network for use with DeepProblog

cuda(device=None)[source]

Mode the network to a cuda device if CUDA is available. :param device: The cuda device to move the network to.

eval()[source]

Set the network to eval mode.

load(location: PathLike | IO[bytes])[source]

Restore the parameters of this network from a file. :param location: The location of the parameter file. :return:

parameters() → Iterator[Parameter][source]

Return the parameters of the network module :return:

save(location: PathLike | IO[bytes], complete=False)[source]

Save the parameters of this network to the given location. :param location: The location to save the parameter file to. :param complete: If true, also save information needed to resume training. :return:

step()[source]

Call the step function of the optimizer :return:

step_epoch()[source]

Call the step function of the scheduler :return:

train()[source]

Set the network to train mode.

zero_grad()[source]

Call zero grad on the optimizer :return:

optimizer

class deepproblog.optimizer.Optimizer(model: Model)[source]

Bases: object

The optimizer responsible for optimizing the neural parameters in the model.

add_parameter_gradient(k, grad: Tensor)[source]

Accumulate the gradient for a probabilistic parameter. :param k: The key of the parameter. :param grad: The gradient to accumulate. :return:

step()[source]

Perform an optimization step for all parameters. :return:

step_epoch()[source]

Perform an epoch step. This calls the step_epoch method of all the networks in the model. :return:

zero_grad()[source]

Zeroes all gradients. :return:

class deepproblog.optimizer.SGD(model: Model, param_lr: float)[source]

Bases: Optimizer

An optimizer that also optimizes the probabilistic parameters in the model using stochastic gradient descent.

add_parameter_gradient(k, grad: Tensor)[source]

Accumulate the gradient for a probabilistic parameter. :param k: The key of the parameter. :param grad: The gradient to accumulate. :return:

get_lr() → float[source]
Returns:

The learning rate for the probabilistic parameters.

step()[source]

Perform an optimization step for all parameters. :return:

model

class deepproblog.model.Model(program_string: str | PathLike, networks: Collection[Network], embeddings: TermEmbedder | None = None, load: bool = True)[source]
add_tensor_source(name: str, source: ImageDataset | Mapping[Any, Tensor])[source]

Adds a named tensor source to the model. :param name: The name of the added tensor source. :param source: The tensor source to add :return:

eval()[source]

Set the mode of all networks in the model to eval.

evaluate_nn(to_evaluate: List[Tuple[Term, Term]])[source]
Parameters:

to_evaluate – List of neural predicates to evaluate

Returns:

A dictionary with the elements of to_evaluate as keys, and the output of the NN as values.

get_hyperparameters() → dict[source]

Recursively build a dictionary containing the most important hyperparameters in the model. :return: A dictionary that contains the values of the most important hyperparameters of the model.

get_tensor(term: Term) → Tensor[source]
Parameters:

term – A term of the form tensor(_).

If the tensor is of the form tensor(a(*args)), then it well look into tensor source a. :return: Returns the stored tensor identifier by the term.

hyperparameters_to_file(filename)[source]

Write the output of the get_hyperparameter() method in JSON format to a file. :param filename: The path to write the hyperparameters to. :return:

load_state(filename: str | PathLike | IO[bytes])[source]
Restore the state of this model from the given filename. This only includes the probabilistic parameters

and all parameters of the neural networks, but not the model architecture or neural architectures.

Parameters:

filename – The filename to restore the model from.

Returns:

save_state(filename: str | PathLike | IO[bytes], complete=False)[source]
Saves the state of this model to a zip file with the given filename. This only includes the probabilistic

parameters and all parameters of the neural networks, but not the model architecture or neural architectures

Parameters:
  • filename – The filename to save the model to.

  • complete – If true, save neural networks with information needed to resume training.

Returns:

set_engine(engine: Engine, **kwargs)[source]

Initializes the solver of this model with the given engine and additional arguments. :param engine: The engine that will be used to ground queries in this model. :param kwargs: Additional arguments passed to the solver. :return:

store_tensor(tensor: Tensor) → Term[source]

Stores a tensor in the tensor store and returns and identifier. :param tensor: The tensor to store. :return: The Term that is the identifier by which this tensor can be uniquely identified in the logic.

train()[source]

Set the mode of all networks in the model to train. :return:

train

evaluate

deepproblog.evaluate.get_confusion_matrix(model: Model, dataset: Dataset, verbose: int = 0, eps: float | None = None) → ConfusionMatrix[source]
Parameters:
  • model – The model to evaluate.

  • dataset – The dataset to evaluate the model on.

  • verbose – Set the verbosity. If verbose > 0, then print confusion matrix and accuracy.

If verbose > 1, then print all wrong answers. :param eps: If set, then the answer will be treated as a float, and will be considered correct if the difference between the predicted and ground truth value is smaller than eps. :return: The confusion matrix when evaluating model on dataset.

deepproblog.evaluate.get_fact_accuracy(model: Model, dataset: Dataset, verbose: int = 0, threshold: float = 0.5, empty_answer: str = 'false') → ConfusionMatrix[source]
Parameters:
  • model – The model to evaluate.

  • dataset – The dataset to evaluate the model on.

  • verbose – Set the verbosity. If verbose > 0, then print confusion matrix and accuracy.

If verbose > 1, then print all wrong answers. :param threshold: If set, then the answer will be treated as a float, and will be considered correct if the difference between the predicted and ground truth value is smaller than eps. :param empty_answer: The category in the confusion matrix when no answer was returned. Default = “false” :return: The confusion matrix when evaluating model on dataset.

solver

class deepproblog.solver.Solver(model: Model, engine: ~deepproblog.engines.engine.Engine, semiring: ~typing.Type[~deepproblog.semiring.Semiring] = <class 'deepproblog.semiring.graph_semiring.GraphSemiring'>, cache: bool = False, cache_root: str | None = None, sdd_auto_gc: bool = False)[source]

Bases: object

A class that bundles the different steps of inference.

build_ac(q: Query) → ArithmeticCircuit[source]

Builds the arithmetic circuit. :param q: The query for which to build the arithmetic circuit. :return: The arithmetic circuit for the given query.

solve(batch: Sequence[Query]) → List[Result][source]

Performs inference for a batch of queries. :param batch: A list of queries to perform inference on. :return: A list of results for the given queries.

exception deepproblog.solver.SolverException(*args: object)[source]

Bases: Exception

engine

class deepproblog.engines.engine.Engine(model: Model)[source]

Bases: object

An asbtract engine base class.

eval()[source]

Set the engine to eval mode. :return:

ground(query: Query, **kwargs) → LogicFormula[source]
Parameters:
  • query – The query to ground.

  • kwargs –

Returns:

A logic formula representing the ground program.

prepare(program: LogicProgram) → LogicProgram[source]

Modifies the given program to a format suited for querying in this engine. :param program: The program to be modified :return: The modified program

register_foreign(func: callable, function_name: str, arity_in: int, arity_out: int)[source]

Makes a Python function available to the grounding engine. :param func: The Python function to be made available. :param function_name: The name of the predicate that will be used to address this function in logic. :param arity_in: The number of input arguments to func :param arity_out The number of return values of func :return:

register_foreign_nondet(func: callable, function_name: str, arity_in: int, arity_out: int)[source]

Makes a Python function available to the grounding engine. :param func: The Python function to be made available. :param function_name: The name of the predicate that will be used to address this function in logic. :param arity_in: The number of input arguments to func :param arity_out The number of return values of func :return:

train()[source]

Set th engine to train mode. :return:

semiring

class deepproblog.semiring.Result(result: Dict[Term, float | Tensor], semiring: Semiring, ground_time: float | None = None, compile_time: float | None = None, eval_time: float | None = None, proof: LogicFormula | None = None)[source]

Bases: object

A class that contains the result and timing info for evaluating a query.

class deepproblog.semiring.Semiring(model, substitution, values)[source]

Bases: Semiring, ABC

The semiring object defines the operations for the evaluation of arithmetic circuits.

abstract static cross_entropy(result: Result, target: float, weight: float, q: Query | None = None, eps: float = 1e-06)[source]

Calculates the cross_entropy between the predicted and target probabilities. Also performs the backwards pass for the given result. :param result: The result to calculate loss on. :param target: The target probability. :param weight: The weight of this examplE. A float that is multiplied with the loss before backpropagation. :param q: If there’s more than one query in result, calculate the loss for this query. :param eps: The epsilon used in the cross-entropy loss calculation. :return:

arithmetic circuit

class deepproblog.arithmetic_circuit.ArithmeticCircuit(formula: LogicFormula, semiring: Type[Semiring] | None, ground_time: float | None = None, sdd_auto_gc: bool = False)[source]
evaluate(model: Model, substitution: dict | None = None, re_evaluate: bool = True) → Result[source]

Evaluates the arithmetic circuit. :param model: The model (neural network and parameters) to evaluate the AC in. :param substitution: Optional dict. The substitution applied to the parameterized AC. See apply_term. :param re_evaluate: Force re-evaluation of the neural networks :return:

extract_neural() → List[Tuple[Term, Term]][source]
Returns:

Returns a set of all neural predicates that need to be evaluated.

get_named() → Dict[Term, int][source]
Returns:

A dictionary mapping all named nodes in the SDD to their node id.