API¶
Public API Reference¶
- symtorch.symtorchify(expr: str | Basic | int | float | bool, trainable: bool = True, trainable_ints: bool = False) Expression[source]¶
Convert a string, SymPy object, or numeric value to a vanilla PyTorch implementation of the expression.
- Parameters:
expr – The expression or value to convert.
trainable – Whether the resulting parameters should be trainable, by default True.
trainable_ints –
Whether integer parameters should be trainable, by default False. Sympy converts e.g. the division operator into a combination of a multiplication and an exponentiation operator:
\[a / b = a * b^{-1}\]The -1 exponent is converted to a
symtorch.Parameterbysymtorch. Iftrainable_intsisTrue, this exponent will be trainable (and hence e.g. \(a/b\) may change during training to be:\[a * (b^{-1.56})\]
- Returns:
The converted SymTorch Expression.
- Return type:
- Raises:
ValueError – If
trainable_intsisTruebuttrainableisFalse.
Examples
Create a simple addition of two symbols:
- symtorch.SymbolicExpression() Expression[source]¶
Create an empty, place-holder
Expression.- Returns:
An empty Expression.
- Return type:
Examples
Use this as a placeholder for a model:
>>> model = SymbolicExpression() >>> model empty
Fill it with a symbolic expression later:
>>> other_model = symtorchify("x + 2.0", trainable=False) >>> model.load_state_dict(other_model.state_dict()) >>> model x + 2.0
- class symtorch.SymbolAssignment(symbol_order: list[str] | None = None)[source]¶
Bases:
ModuleConvert a tensor into a dictionary of symbols.
This module converts a tensor
Xof shape(..., N)into a dictionary of symbols,{s: X[..., [i]]}, wheresis thei’th symbol in symbol_order.- Parameters:
symbol_order – The order of symbols to use for assignment, by default None.
Examples
Use a
SymbolAssignmentmodule in combination with aSymbolicExpressionwithin atorch.nn.Sequentialmodule to create a simple model:>>> model = torch.nn.Sequential( ... SymbolAssignment(["x", "y"]), ... symtorchify("x**2 + 2*y") ... ) >>> input = torch.arange(10).reshape(5, 2) >>> model(input) tensor([[ 2], [10], [26], [50], [82]])
- class symtorch.Expression[source]¶
Bases:
SymbolicModuleA tree-based, PyTorch-compatible implementation of a symbolic expression, where each leaf node is a
SymbolorParameter, and each internal node is anotherExpression.- nodes¶
The child nodes of the expression tree.
- Type:
Sequence[SymbolicModule]
Internal API Reference¶
- class symtorch.Parameter[source]¶
Bases:
SymbolicModuleA symbolic parameter, i.e. a leaf node in the expression tree.
- param¶
The underlying value of the parameter.
- Type:
torch.nn.Parameter
- class symtorch.Symbol[source]¶
Bases:
SymbolicModuleA symbolic variable, i.e. a leaf node in the expression tree.
- class symtorch.operations.Operation[source]¶
-
Abstract base class for all
torchequivalents of SymPy operations.
- class symtorch.operations.UnaryOperation[source]¶
-
ABC for all
torchequivalents of SymPy unary operations.