5from dataclasses
import dataclass
6from math
import isfinite
7from operator
import index
12 "add": (2, np.add,
"+"),
13 "sub": (2, np.subtract,
"-"),
14 "mul": (2, np.multiply,
"*"),
15 "div": (2, np.divide,
"/"),
16 "neg": (1, np.negative,
"-"),
17 "square": (1, np.square,
""),
18 "sqrt": (1, np.sqrt,
"sqrt"),
19 "sin": (1, np.sin,
"sin"),
20 "cos": (1, np.cos,
"cos"),
21 "exp": (1, np.exp,
"exp"),
22 "log": (1, np.log,
"log"),
24_NON_ALGEBRAIC = frozenset((
"sin",
"cos",
"exp",
"log"))
28@dataclass(frozen=True, order=True, slots=True)
30 """Define an immutable equation tree.
32 Leaves are made with :meth:`variable`, :meth:`constant`, and
33 :meth:`parameter`. Each parameter leaf occupies a separate slot in
34 left-to-right traversal order, even if the same leaf object is reused.
36 For an operation, supply its name and its children. Binary operations
37 are ``add``, ``sub``, ``mul``, and ``div``. Unary operations are
38 ``neg``, ``square``, ``sqrt``, ``sin``, ``cos``, ``exp``, and ``log``.
42 children: tuple[
"Expression", ...] = ()
43 value: int | float |
None =
None
45 def __post_init__(self):
47 object.__setattr__(self,
"children", children)
48 if self.
op in (
"variable",
"constant",
"parameter"):
50 raise ValueError(
"Expression leaves cannot have children.")
51 if self.
op ==
"variable":
52 column = index(self.
value)
54 raise ValueError(
"Variable indices must be nonnegative.")
55 object.__setattr__(self,
"value", column)
56 elif self.
op ==
"constant":
57 number = float(self.
value)
58 if not isfinite(number):
59 raise ValueError(
"Expression constants must be finite.")
60 object.__setattr__(self,
"value", number)
61 elif self.
value is not None:
62 raise ValueError(
"A parameter leaf takes its value from the fitted coefficients.")
63 elif (self.
op not in _OPERATORS
or self.
value is not None
64 or len(children) != _OPERATORS[self.
op][0]
65 or not all(isinstance(child, Expression)
for child
in children)):
66 raise ValueError(f
"Invalid expression operation or operands: {self.op!r}.")
70 def variable(cls, column: int) ->
"Expression":
71 """Return a leaf that reads the given zero-based column of the input."""
72 return cls(
"variable", value=column)
77 """Return a free scalar leaf, with a separate coefficient for each occurrence."""
78 return cls(
"parameter")
82 def constant(cls, value: float) ->
"Expression":
83 """Return a fixed real-valued leaf."""
84 return cls(
"constant", value=value)
89 """Count all operator and terminal occurrences."""
90 return 1 + sum(child.node_count
for child
in self.
children)
95 """Count free coefficient occurrences."""
96 return sum(child.parameter_count
for child
in self.
children) + (self.
op ==
"parameter")
101 """Count sine, cosine, exponential, and logarithm occurrences."""
102 return sum(child.non_algebraic_count
for child
in self.
children) + (self.
op in _NON_ALGEBRAIC)
106 """Validate finite real inputs with one row per sample and one column per variable."""
107 values = np.asarray(data)
108 if np.iscomplexobj(values):
109 raise ValueError(
"X must contain real values.")
110 x = np.asarray(values, dtype=float)
111 if x.ndim != 2
or not all(x.shape)
or not np.isfinite(x).all():
112 raise ValueError(
"X must be a nonempty, finite (samples, variables) matrix.")
116def _compile(expression):
117 """Build a postfix program and a structurally affine subset of parameter slots."""
123 nonlocal n_parameters, n_variables
124 op, value = node.op, node.value
125 if op ==
"parameter":
128 program.append((op, slot))
131 n_variables = max(n_variables, value + 1)
132 affine = [visit(child)
for child
in node.children]
133 program.append((op, value))
134 if op
in (
"add",
"sub"):
135 return affine[0] + affine[1]
136 if op
in (
"div",
"neg"):
140 return max(affine, key=len)
143 linear = visit(expression)
144 return tuple(program), linear, n_parameters, n_variables
147def _constant_column(values, width):
148 basis = np.zeros((len(values), width))
153def _evaluate(program, x, coefficients, affine=None):
154 """Interpret the tree in vector form or as [offset, basis] for affine fitting."""
156 with np.errstate(all=
"ignore"):
157 for op, value
in program:
159 stack.append(x[:, value])
160 elif op ==
"constant":
161 stack.append(np.broadcast_to(value, len(x)))
162 elif op ==
"parameter":
163 if affine
and value
in affine:
164 basis = np.zeros((len(x), len(affine) + 1))
165 basis[:, affine[value]] = 1.
168 stack.append(np.broadcast_to(coefficients[value], len(x)))
170 arity, fn, _ = _OPERATORS[op]
172 result = fn(stack.pop())
174 right, left = stack.pop(), stack.pop()
175 if left.ndim != right.ndim:
176 if op
in (
"add",
"sub"):
178 left = _constant_column(left, right.shape[1])
180 right = _constant_column(right, left.shape[1])
185 right = right[:,
None]
186 result = fn(left, right)
188 stack.append(np.where(np.isfinite(result), result, np.nan))
192def _rmse(predictions, target):
193 if not np.isfinite(predictions).all():
195 with np.errstate(over=
"ignore"):
196 errors = np.abs(predictions - target)
197 scale = float(np.max(errors))
200 if not isfinite(scale):
201 scale = max(float(np.max(np.abs(predictions))), float(np.max(np.abs(target))))
202 errors = np.abs(predictions / scale - target / scale)
205 return scale * float(np.sqrt(np.mean(np.square(errors))))
208def _render(expression, coefficients):
209 if expression.op ==
"variable":
210 return f
"x{expression.value}"
211 if expression.op ==
"constant":
212 return repr(expression.value)
213 if expression.op ==
"parameter":
214 return repr(next(coefficients))
215 operands = [_render(child, coefficients)
for child
in expression.children]
216 arity, _, symbol = _OPERATORS[expression.op]
218 return f
"({operands[0]} {symbol} {operands[1]})"
219 if expression.op ==
"square":
220 return f
"({operands[0]})**2"
221 return f
"{symbol}({operands[0]})"
225@dataclass(frozen=True, slots=True)
227 """Store a tree, its fitted coefficients, and its training RMSE.
229 Coefficients follow the leaf order of :class:`Expression`. Models
230 contain no training data or optimizer state.
233 expression: Expression
234 coefficients: tuple[float, ...]
237 def __post_init__(self):
239 if len(coefficients) != self.
expression.parameter_count
or not all(map(isfinite, coefficients)):
240 raise ValueError(
"Supply a finite coefficient for each parameter leaf.")
242 raise ValueError(
"The training RMSE must be finite and nonnegative.")
243 object.__setattr__(self,
"coefficients", coefficients)
248 """Format the fitted expression with variable names x0, x1, and so on."""
255 """Predict one value per row. Undefined or overflowing rows return NaN."""
257 program, _, _, n_variables = _compile(self.
expression)
258 if x.shape[1] < n_variables:
259 raise ValueError(f
"The expression needs at least {n_variables} input columns.")
267 """Return RMSE on labeled rows, or infinity if any prediction is undefined."""
269 return _rmse(predictions, _target(y, len(predictions)))
273 values = np.asarray(y)
274 if np.iscomplexobj(values):
275 raise ValueError(
"y must contain real values.")
276 target = np.asarray(values, dtype=float)
277 if target.shape != (n,)
or not np.isfinite(target).all():
278 raise ValueError(
"y must be a finite vector with one target per input row.")
A safe expression tree whose parameter leaves each hold one free scalar.
int parameter_count(self)
Count independent parameter slots.
"Expression" parameter(cls)
Build a free coefficient leaf.
"Expression" variable(cls, int column)
Build a variable leaf from a zero-based input column.
"Expression" constant(cls, float value)
Build a fixed, finite numeric leaf.
int node_count(self)
Count all nodes, including leaves.
int non_algebraic_count(self)
Count trigonometric, exponential and logarithmic nodes.
A fitted expression with independently usable NumPy inference.
float rmse(self, X, y)
Score the model on a separate labeled dataset.
str formula(self)
Format the equation with its fitted coefficients.
np.ndarray predict(self, X)
Vectorized evaluation with original operator domains.