SR Dataset
SRToolkit.dataset.sr_dataset
Dataset wrapper for a single symbolic regression problem.
SR_dataset
SR_dataset(X: ndarray, symbol_library: SymbolLibrary, ranking_function: str = 'rmse', y: Optional[ndarray] = None, max_evaluations: int = -1, ground_truth: Optional[Union[List[str], Node, ndarray]] = None, original_equation: Optional[str] = None, success_threshold: Optional[float] = None, seed: Optional[int] = None, dataset_metadata: Optional[dict] = None, dataset_name: str = 'unnamed', samplers: Optional[List[Sampler]] = None, benchmark: Optional[str] = None, version: Optional[str] = None, **kwargs: Unpack[EstimationSettings])
Wraps input data and evaluation settings for a single symbolic regression problem.
Examples:
>>> X = np.array([[1, 2], [3, 4], [5, 6]])
>>> dataset = SR_dataset(X, SymbolLibrary.default_symbols(2), ground_truth=["X_0", "+", "X_1"],
... y=np.array([3, 7, 11]), max_evaluations=10000, original_equation="z = x + y", success_threshold=1e-6)
>>> evaluator = dataset.create_evaluator()
>>> bool(evaluator.evaluate_expr(["sin", "(", "X_0", ")"]) < dataset.success_threshold)
False
>>> bool(evaluator.evaluate_expr(["u-", "C", "*", "X_1", "+", "X_0"]) < dataset.success_threshold)
True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input data of shape |
required |
symbol_library
|
SymbolLibrary
|
The symbol library defining the tokens used for the discovery task. |
required |
ranking_function
|
str
|
Ranking function to use. |
'rmse'
|
y
|
Optional[ndarray]
|
Target values used for parameter estimation when |
None
|
max_evaluations
|
int
|
Maximum number of expressions to evaluate. Values less than 0 mean no limit. |
-1
|
ground_truth
|
Optional[Union[List[str], Node, ndarray]]
|
The ground truth expression, as a list of tokens in infix notation, a
Node tree, or a numpy array of behavior matrix
(see create_behavior_matrix).
Numpy array is only applicable when |
None
|
original_equation
|
Optional[str]
|
Human-readable string of the original equation (e.g. |
None
|
success_threshold
|
Optional[float]
|
Error threshold below which an expression is considered successful. If |
None
|
seed
|
Optional[int]
|
Random seed for reproducibility. |
None
|
dataset_metadata
|
Optional[dict]
|
Optional dictionary of metadata about the dataset (e.g. citation, variable names). |
None
|
dataset_name
|
str
|
Name for this dataset. Defaults to |
'unnamed'
|
samplers
|
Optional[List[Sampler]]
|
Optional list of Sampler instances (one per input variable). The built-in LogUniformSampling, UniformSampling, and IntegerUniformSampling implement this interface. |
None
|
benchmark
|
Optional[str]
|
Optional benchmark name (e.g. |
None
|
version
|
Optional[str]
|
Optional version string (e.g. |
None
|
**kwargs
|
Unpack[EstimationSettings]
|
Optional estimation settings passed to
SR_evaluator.
Supported keys: |
{}
|
Source code in SRToolkit/dataset/sr_dataset.py
evaluate_approach
evaluate_approach(sr_approach: SR_approach, num_experiments: int = 1, top_k: int = 20, initial_seed: Optional[int] = None, results: Optional[SR_results] = None, callbacks: Optional[Union[SRCallbacks, CallbackDispatcher, List[SRCallbacks]]] = None, verbose: bool = True, adaptation_path: Optional[str] = None) -> SR_results
Evaluates an SR approach on this dataset.
Examples:
>>> X = np.array([[1, 2], [3, 4], [5, 6]])
>>> dataset = SR_dataset(X, SymbolLibrary.default_symbols(2), ground_truth=["X_0", "+", "X_1"],
... y=np.array([3, 7, 11]), max_evaluations=10000, original_equation="z = x + y")
>>> results = dataset.evaluate_approach(my_approach, num_experiments=5)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sr_approach
|
SR_approach
|
The SR approach to evaluate. |
required |
num_experiments
|
int
|
Number of independent experiments (runs) to perform. |
1
|
top_k
|
int
|
Number of top expressions to retain per experiment. |
20
|
initial_seed
|
Optional[int]
|
Seed for random number generation. If |
None
|
results
|
Optional[SR_results]
|
Existing SR_results object to append
results to. If |
None
|
callbacks
|
Optional[Union[SRCallbacks, CallbackDispatcher, List[SRCallbacks]]]
|
Optional list of SRCallbacks, SRCallbacks, or CallbackDispatcher for monitoring and controlling the search. |
None
|
verbose
|
bool
|
If |
True
|
adaptation_path
|
Optional[str]
|
Path to save/load the adapted state for approaches with
|
None
|
Returns:
| Type | Description |
|---|---|
SR_results
|
An SR_results object containing results from all experiments. |
Source code in SRToolkit/dataset/sr_dataset.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |
create_evaluator
create_evaluator(metadata: Optional[Dict[str, Any]] = None, seed: Optional[int] = None) -> SR_evaluator
Creates an instance of the SR_evaluator class from this dataset.
Examples:
>>> X = np.array([[1, 2], [3, 4], [5, 6]])
>>> dataset = SR_dataset(X, SymbolLibrary.default_symbols(2), ground_truth=["X_0", "+", "X_1"],
... y=np.array([3, 7, 11]), max_evaluations=10000, original_equation="z = x + y", success_threshold=1e-6)
>>> evaluator = dataset.create_evaluator()
>>> float(evaluator.evaluate_expr(["sin", "(", "X_0", ")"]))
8.05645397...
>>> float(evaluator.evaluate_expr(["X_1", "+", "X_0"]))
0.0...
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
Optional[Dict[str, Any]]
|
Optional dictionary of metadata to attach to the evaluator (e.g. model name, seed). Dataset metadata is merged in automatically. |
None
|
seed
|
Optional[int]
|
Seed for the random number generator. If |
None
|
Returns:
| Type | Description |
|---|---|
SR_evaluator
|
A configured SR_evaluator ready to evaluate expressions against this dataset. |
Raises:
| Type | Description |
|---|---|
Exception
|
If SR_evaluator cannot be instantiated with the current dataset settings. |
Source code in SRToolkit/dataset/sr_dataset.py
__str__
Returns a string describing this dataset.
The string describes the target expression, symbols that should be used, and the success threshold. It also includes any constraints that should be followed when evaluating a model on this dataset. These constraints include the maximum number of expressions to evaluate, the maximum length of the expression, and the maximum number of constants allowed in the expression. If the symbol library contains a symbol for constants, the string also includes the range of constants.
For other metadata, please refer to the attribute self.dataset_metadata.
Examples:
>>> X = np.array([[1, 2], [3, 4], [5, 6]])
>>> dataset = SR_dataset(X, SymbolLibrary.default_symbols(2), ground_truth=["X_0", "+", "X_1"],
... y=np.array([3, 7, 11]), max_evaluations=10000, original_equation="z = x + y", success_threshold=1e-6)
>>> str(dataset)
'Dataset for target expression z = x + y. When evaluating your model on this dataset, you should limit your generative model to only produce expressions using the following symbols: +, -, *, /, ^, u-, sqrt, sin, cos, exp, tan, arcsin, arccos, arctan, sinh, cosh, tanh, floor, ceil, ln, log, ^-1, ^2, ^3, ^4, ^5, pi, e, C, X_0, X_1.\nExpressions will be ranked based on the RMSE ranking function.\nExpressions are deemed successful if the root mean squared error is less than 1e-06. However, we advise that you check the best performing expressions manually to ensure they are correct.\nDataset uses the default limitations (extra arguments) from the SR_evaluator.The expressions in the dataset can contain constants/free parameters.\nFor other metadata, please refer to the attribute self.dataset_metadata.'
Returns:
| Type | Description |
|---|---|
str
|
A string describing this dataset. |
Source code in SRToolkit/dataset/sr_dataset.py
resample
Generate fresh data by applying the stored samplers to produce new inputs.
For ranking_function="rmse", the ground truth expression is also evaluated and
(X, y) is returned. For ranking_function="bed", only X is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of samples to generate. |
required |
seed
|
Optional[int]
|
Random seed for reproducibility. If |
None
|
Returns:
| Type | Description |
|---|---|
Union[ndarray, Tuple[ndarray, ndarray]]
|
For RMSE: a tuple |
Union[ndarray, Tuple[ndarray, ndarray]]
|
For BED: a single array |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in SRToolkit/dataset/sr_dataset.py
resample_inplace
Resample via the stored samplers and write the result back into self.X/self.y.
A convenience wrapper around resample
that handles the RMSE (X, y) vs BED X-only return shapes. For BED datasets,
self.y is set to None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of samples to generate. |
required |
seed
|
Optional[int]
|
Random seed for reproducibility. If |
None
|
Returns:
| Type | Description |
|---|---|
SR_dataset
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Propagated from resample
if |
Source code in SRToolkit/dataset/sr_dataset.py
to_dict
Creates a JSON-safe dictionary representation of this dataset.
The data arrays are not embedded in the dictionary — they live in the data cache (see data_cache). Use from_dict to reconstruct the full dataset including data.
When data_source is None the in-memory arrays are the only copy of the
data, so calling this method writes them into the cache version directory (via
the private _persist_to_cache helper) so the returned config stays
reloadable. For
SampleSource /
UrlSource datasets there are no arrays
to write and the call has no filesystem side effects.
Examples:
>>> X = np.array([[1, 2], [3, 4], [5, 6]])
>>> dataset = SR_dataset(X, SymbolLibrary.default_symbols(2), ground_truth=["X_0", "+", "X_1"],
... y=np.array([3, 7, 11]), max_evaluations=10000, original_equation="z = x + y",
... success_threshold=1e-6, benchmark="test", version="1.0.0")
>>> d = dataset.to_dict()
>>> d["format_version"]
2
>>> d["benchmark"]
'test'
Returns:
| Type | Description |
|---|---|
dict
|
A JSON-safe dictionary representing this dataset's configuration. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValueError
|
If |
Source code in SRToolkit/dataset/sr_dataset.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 | |
from_dict
classmethod
Creates an instance of the SR_dataset class from its dictionary representation.
If d is a string or Path, it is treated as a JSON file path and read
from disk. To load a self-contained .zip archive (written by
to_archive) use
from_archive instead.
The data arrays are loaded from the data cache (or materialised on demand).
Examples:
>>> import tempfile, os, json
>>> from SRToolkit.dataset.sampling import UniformSampling
>>> from SRToolkit.dataset.data_source import SampleSource
>>> X = np.array([[1, 2], [3, 4], [5, 6]], dtype=float)
>>> ds = SR_dataset(X, SymbolLibrary.default_symbols(2), ground_truth=["X_0", "+", "X_1"],
... y=np.array([3, 7, 11], dtype=float), max_evaluations=10000, original_equation="z = x + y",
... success_threshold=1e-6, benchmark="test_bench", version="1.0.0",
... samplers=[UniformSampling(0, 5), UniformSampling(0, 5)])
>>> ds.data_source = SampleSource(n_samples=3, seed=0)
>>> d = ds.to_dict()
>>> ds2 = SR_dataset.from_dict(d)
>>> ds2.benchmark
'test_bench'
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Union[dict, str, Path]
|
Dictionary produced by to_dict, or a path to a JSON file containing such a dictionary. |
required |
Returns:
| Type | Description |
|---|---|
SR_dataset
|
A new SR_dataset instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the |
FileNotFoundError
|
If the cached data file does not exist and |
Source code in SRToolkit/dataset/sr_dataset.py
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 | |
to_archive
Write this dataset (config + data) to a self-contained .zip archive.
The archive mirrors the per-dataset layout of SR_benchmark.to_archive and contains:
dataset.json: this dataset's configuration dict (see to_dict).data/<dataset_name>.npz: theX(andyfor RMSE) arrays.data/<dataset_name>_gt.npy: ground-truth behaviour array, only whenground_truthis a numpy array (abedbehaviour matrix).
Load it back with from_archive, or from a URL with from_url.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Destination path for the archive. A non- |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in SRToolkit/dataset/sr_dataset.py
from_archive
classmethod
Load a dataset from a self-contained .zip archive.
This is the counterpart to
to_archive: it reads
dataset.json from the archive, extracts the bundled data/*.npz (and any
_gt.npy) into the data cache, and reconstructs the dataset from them. Unlike
from_dict, no
data_source materialisation is needed — the data travels inside the archive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Path to a |
required |
Returns:
| Type | Description |
|---|---|
SR_dataset
|
A new SR_dataset instance. |
Source code in SRToolkit/dataset/sr_dataset.py
from_url
classmethod
Download a self-contained .zip archive from a URL and load it.
This is the remote counterpart to
from_archive: the archive
is downloaded to a temporary file and then loaded exactly as from_archive
would. The url must point at an archive written by
to_archive (a
dataset.json plus a data/ directory) — not a bare .npz/data zip
(that is what UrlSource is for).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL of a |
required |
Returns:
| Type | Description |
|---|---|
SR_dataset
|
A new SR_dataset instance. |
Source code in SRToolkit/dataset/sr_dataset.py
from_samplers
classmethod
from_samplers(ground_truth: Union[List[str], Node], samplers: List[Sampler], symbol_library: Optional[SymbolLibrary] = None, n_samples: int = 10000, seed: Optional[int] = None, ranking_function: str = 'rmse', original_equation: Optional[str] = None, success_threshold: Optional[float] = None, max_evaluations: int = -1, dataset_name: str = 'unnamed', dataset_metadata: Optional[dict] = None, benchmark: Optional[str] = None, version: Optional[str] = None, **kwargs: Unpack[EstimationSettings]) -> SR_dataset
Build a dataset from just a ground-truth expression and per-variable samplers.
This is the convenience constructor for the common case where you have the
expression you want to recover and a sampling spec for its inputs, but no data
arrays yet. The inputs X are drawn from samplers (one per variable) and,
for ranking_function="rmse", the targets y are produced by evaluating
ground_truth on them. The result carries a
SampleSource, so it round-trips via
to_dict, regenerates with
refresh, and resamples with
resample.
Examples:
>>> from SRToolkit.dataset.sampling import UniformSampling
>>> ds = SR_dataset.from_samplers(["X_0", "+", "X_1"],
... [UniformSampling(0, 5), UniformSampling(0, 5)], n_samples=100, seed=0)
>>> ds.X.shape
(100, 2)
>>> ds.y.shape
(100,)
>>> ds.original_equation
'y = X_0+X_1'
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ground_truth
|
Union[List[str], Node]
|
The ground-truth expression as a list of infix tokens or a
Node. For |
required |
samplers
|
List[Sampler]
|
One Sampler per input variable. |
required |
symbol_library
|
Optional[SymbolLibrary]
|
Token vocabulary. Defaults to default_symbols with one variable per sampler. |
None
|
n_samples
|
int
|
Number of input rows to generate. Defaults to |
10000
|
seed
|
Optional[int]
|
Random seed for the generation (stored on the
SampleSource). |
None
|
ranking_function
|
str
|
|
'rmse'
|
original_equation
|
Optional[str]
|
Human-readable equation string. If |
None
|
success_threshold
|
Optional[float]
|
Error threshold for success. |
None
|
max_evaluations
|
int
|
Maximum expressions to evaluate. |
-1
|
dataset_name
|
str
|
Name for this dataset. |
'unnamed'
|
dataset_metadata
|
Optional[dict]
|
Optional dataset-level metadata dict. |
None
|
benchmark
|
Optional[str]
|
Optional benchmark name (needed only for serialisation). |
None
|
version
|
Optional[str]
|
Optional version string (needed only for serialisation). |
None
|
**kwargs
|
Unpack[EstimationSettings]
|
Estimation settings forwarded to SR_evaluator. |
{}
|
Returns:
| Type | Description |
|---|---|
SR_dataset
|
A new SR_dataset with freshly |
SR_dataset
|
generated data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in SRToolkit/dataset/sr_dataset.py
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 | |
refresh
Force-refresh the cached data for this dataset by re-materialising it
from data_source.
After refreshing, self.X and self.y are reloaded from the new cache.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |