Dataset Submodule
SRToolkit.dataset
Datasets and benchmarks for symbolic regression.
A dataset (SR_dataset) represents a single equation with associated data, a symbol library, and evaluation constraints. A benchmark (SR_benchmark) is a collection of datasets.
Modules:
| Name | Description |
|---|---|
sr_dataset |
SR_dataset — wraps input data and evaluation settings for a single equation discovery problem. |
sr_benchmark |
SR_benchmark — manages a collection of datasets. |
feynman |
Feynman — 100-equation physics benchmark. |
nguyen |
Nguyen — 10-equation polynomial/trig benchmark. |
srsd_feynman |
SRSD_Feynman — 120-equation SRSD physics benchmark with per-variable sampling strategies. |
sampling |
LogUniformSampling, UniformSampling, IntegerUniformSampling — variable samplers with serialisation support. |
data_source |
DataSource and its concrete types UrlSource and SampleSource — describe where a dataset's cached data originates. |
data_cache |
dataset cache management — list, gc, remove, refresh, dataset_path — plus the materialisation engine used internally by the dataset machinery. |
DataSource
Bases: ABC
Abstract base class describing the origin of a dataset's cached data.
Concrete subclasses must implement
to_dict,
from_dict, and
materialize. The dict produced
by to_dict must include a "source_class" key holding the fully-qualified class
path (e.g. "SRToolkit.dataset.data_source.UrlSource") so that
DataSource.from_dict can reconstruct it
via importlib without a central registry.
The cache layer stores a hash of every source's data_source + samplers config
and warns when it drifts from what the cache was built with — regardless of this flag —
so a changed url, changed n_samples/seed, or a switch between source kinds is
always surfaced.
Attributes:
| Name | Type | Description |
|---|---|---|
is_volatile |
bool
|
Informational hint: |
to_dict
abstractmethod
Serialize this source to a JSON-compatible dictionary.
The returned dict must include "source_class" set to the fully-qualified
class path of this source.
from_dict
classmethod
Reconstruct a source from a dict produced by to_dict.
When called on the base DataSource
class, dispatches to the concrete subclass named by the "source_class" key
using importlib — both built-in and user-defined subclasses round-trip without
a central registry. When called on a concrete subclass, that subclass must override
this method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Optional[dict]
|
Dictionary with a |
required |
Returns:
| Type | Description |
|---|---|
Optional['DataSource']
|
A reconstructed DataSource instance, |
Optional['DataSource']
|
or |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ImportError
|
If the class cannot be imported (dispatch path). |
NotImplementedError
|
If called on a subclass that has not overridden this method. |
Source code in SRToolkit/dataset/data_source.py
materialize
abstractmethod
Produce the dataset's data at cache_path (an .npz file with X and,
for RMSE datasets, y).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_path
|
Path
|
Target |
required |
config
|
dict
|
The full serialised dataset config (see
SR_dataset.to_dict).
Sources that generate data (e.g.
SampleSource) read the
dataset's |
required |
Source code in SRToolkit/dataset/data_source.py
FallbackSource
Bases: DataSource
A chain of data sources tried in order until one succeeds.
materialize attempts each
source's materialize in turn; if one raises, a warning is emitted and the next is
tried. The first to succeed wins; if all fail, a RuntimeError chaining the last
error is raised.
The built-in benchmarks use this to prefer canonical downloaded data while keeping a
network-free fallback —
FallbackSource([UrlSource(archive), SampleSource(seed=...)]) downloads the
authoritative archive when reachable and regenerates from the dataset's samplers
otherwise. Because the whole chain is serialised in the config, the preference
travels: a grid recipe, an export, or
a cold worker each download the canonical data first and only sample if it is
unavailable — unlike a bare SampleSource, which would always regenerate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sources
|
List[DataSource]
|
Ordered, non-empty list of DataSource to try. |
required |
Source code in SRToolkit/dataset/data_source.py
to_dict
Serialize this source and its whole chain to a JSON-compatible dictionary.
Source code in SRToolkit/dataset/data_source.py
from_dict
classmethod
Deserialize a FallbackSource, reconstructing each child source.
Source code in SRToolkit/dataset/data_source.py
materialize
Try each source in order; warn and continue on failure, re-raising if all fail.
Source code in SRToolkit/dataset/data_source.py
SampleSource
Bases: DataSource
Data generated by drawing n_samples points from the dataset's samplers.
This source does not own the samplers — it carries only the generation parameters
and reads the samplers from the dataset config at materialisation time. The dataset
must therefore define samplers (one per input variable). For RMSE datasets with a
token-list ground truth, the targets y are produced by evaluating that expression
on the generated inputs.
Because the output depends on the samplers and seed, this source is volatile: the cache layer records a hash and warns when the configuration drifts (call refresh to regenerate).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
Number of input rows to generate. Defaults to |
10000
|
seed
|
Optional[int]
|
Random seed for reproducible generation. |
None
|
Source code in SRToolkit/dataset/data_source.py
to_dict
Serialize this source to a JSON-compatible dictionary.
from_dict
classmethod
Deserialize a SampleSource from a dictionary.
Source code in SRToolkit/dataset/data_source.py
materialize
Generate X (and y for RMSE) from the dataset's samplers and save them.
Source code in SRToolkit/dataset/data_source.py
UrlSource
Bases: DataSource
Data downloaded as a .zip archive from a URL and extracted into the cache.
Two archive layouts are accepted transparently: a flat zip whose
<dataset_name>.npz files sit at the root (as served by the built-in benchmarks),
or a to_archive archive whose data lives under a data/ prefix (in which case
the prefix is stripped and the bundled benchmark.json / dataset.json is
ignored). Either way, the expected <dataset_name>.npz must end up in the version directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL of a |
required |
to_dict
from_dict
classmethod
Deserialize a UrlSource from a dictionary.
Source code in SRToolkit/dataset/data_source.py
materialize
Download the archive and extract its data files into the version directory.
Source code in SRToolkit/dataset/data_source.py
Feynman
Bases: SR_benchmark
The Feynman symbolic regression benchmark.
Contains 100 physics equations with up to 9 variables. Data is downloaded on first use from
the SymbolicRegressionToolkit repository (10,000 samples per dataset instead of the original
1,000,000 from the paper). If the download fails, data is generated from the stored per-variable
samplers using n_samples points and the given seed.
References
Examples:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
Number of samples to generate per dataset when |
10000
|
seed
|
Optional[int]
|
Random seed used for sampler-based data generation. Defaults to |
42
|
force_generate
|
bool
|
If |
False
|
Source code in SRToolkit/dataset/feynman.py
Nguyen
Bases: SR_benchmark
The Nguyen symbolic regression benchmark.
Contains 10 expressions without constant parameters (first 4 are polynomials, first 8 use
one variable, last 2 use two variables). The benchmark ships with pre-generated data. If the
download fails, data is generated from the stored per-variable samplers using n_samples
points and the given seed.
References
Examples:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
Number of samples to generate per dataset when |
10000
|
seed
|
Optional[int]
|
Random seed used for sampler-based data generation. Defaults to |
42
|
force_generate
|
bool
|
If |
False
|
Source code in SRToolkit/dataset/nguyen.py
IntegerUniformSampling
IntegerUniformSampling(min_value: int, max_value: int, uses_positive: bool = True, uses_negative: bool = True)
Bases: Sampler
Integer uniform sampler with configurable sign constraints.
Samples integers from :math:\{\text{min}, ..., \text{max}-1\}, optionally drawing
from positive and/or negative ranges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_value
|
int
|
Lower bound of the integer range. |
required |
max_value
|
int
|
Upper bound (exclusive) of the integer range. |
required |
uses_positive
|
bool
|
If |
True
|
uses_negative
|
bool
|
If |
True
|
Source code in SRToolkit/dataset/sampling.py
to_dict
Serialize this sampler to a JSON-compatible dictionary.
Source code in SRToolkit/dataset/sampling.py
from_dict
classmethod
Deserialize a IntegerUniformSampling from a dictionary produced by to_dict.
Source code in SRToolkit/dataset/sampling.py
LogUniformSampling
LogUniformSampling(min_value: float, max_value: float, uses_positive: bool = True, uses_negative: bool = True)
Bases: Sampler
Log-uniform sampler with configurable sign constraints.
Samples from U(\log_{10}(\text{min}), \log_{10}(\text{max})) in log space,
optionally drawing from positive and/or negative ranges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_value
|
float
|
Lower bound of the log-uniform range (must be > 0). |
required |
max_value
|
float
|
Upper bound of the log-uniform range (must be > 0). |
required |
uses_positive
|
bool
|
If |
True
|
uses_negative
|
bool
|
If |
True
|
Source code in SRToolkit/dataset/sampling.py
to_dict
Serialize this sampler to a JSON-compatible dictionary.
Source code in SRToolkit/dataset/sampling.py
from_dict
classmethod
Deserialize a LogUniformSampling from a dictionary produced by to_dict.
Source code in SRToolkit/dataset/sampling.py
Sampler
Bases: ABC
Abstract base class for variable samplers.
Concrete subclasses must implement __call__,
to_dict, and
from_dict. The dictionary produced by
to_dict must include a "sampler_class"
key holding the fully-qualified class path (e.g.
"SRToolkit.dataset.sampling.UniformSampling"), so that
Sampler.from_dict can reconstruct any
subclass — including user-defined ones — via importlib without a central registry.
__call__
abstractmethod
to_dict
abstractmethod
Serialize this sampler to a JSON-compatible dictionary.
The returned dict must include "sampler_class" set to the
fully-qualified class path of this sampler.
from_dict
classmethod
Reconstruct a sampler from a dictionary produced by to_dict.
When called on the base Sampler class,
dispatches to the concrete subclass named by the "sampler_class" key using
importlib — both built-in and user-defined subclasses round-trip without a
central registry. When called on a concrete subclass, that subclass must override
this method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
Dictionary with a |
required |
Returns:
| Type | Description |
|---|---|
Sampler
|
A reconstructed Sampler instance. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ImportError
|
If the class cannot be imported (dispatch path). |
NotImplementedError
|
If called on a subclass that has not overridden this method. |
Source code in SRToolkit/dataset/sampling.py
UniformSampling
UniformSampling(min_value: float, max_value: float, uses_positive: bool = True, uses_negative: bool = True)
Bases: Sampler
Linear uniform sampler with configurable sign constraints.
Samples fromU(\text{min}, \text{max}), optionally drawing from positive
and/or negative ranges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_value
|
float
|
Lower bound of the uniform range. |
required |
max_value
|
float
|
Upper bound of the uniform range. |
required |
uses_positive
|
bool
|
If |
True
|
uses_negative
|
bool
|
If |
True
|
Source code in SRToolkit/dataset/sampling.py
to_dict
Serialize this sampler to a JSON-compatible dictionary.
Source code in SRToolkit/dataset/sampling.py
from_dict
classmethod
Deserialize a UniformSampling from a dictionary produced by to_dict.
Source code in SRToolkit/dataset/sampling.py
SR_benchmark
SR_benchmark(benchmark_name: str, datasets: Optional[List[Union[SR_dataset, Tuple[str, SR_dataset]]]] = None, metadata: Optional[Dict[str, Any]] = None, version: str = '1.0.0', base_dir: Optional[str] = None)
A named, persistent collection of symbolic regression datasets.
Examples:
>>> from SRToolkit.dataset import Feynman
>>> benchmark = Feynman() # Feynman is a specific instance of SR_benchmark with additional functionality
>>> len(benchmark.list_datasets(verbose=False))
100
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
benchmark_name
|
str
|
Name of this benchmark. |
required |
datasets
|
Optional[List[Union[SR_dataset, Tuple[str, SR_dataset]]]]
|
Initial datasets to add. Each element can be an
SR_dataset instance (auto-named as
|
None
|
metadata
|
Optional[Dict[str, Any]]
|
Optional dictionary of benchmark-level metadata (e.g. citation, description). |
None
|
version
|
str
|
Version string for this benchmark. Defaults to |
'1.0.0'
|
base_dir
|
Optional[str]
|
Directory where dataset files are stored or will be written. Optional — if omitted, the data cache is used exclusively. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If any element of |
Source code in SRToolkit/dataset/sr_benchmark.py
add_dataset_instance
Adds an instance of the SR_dataset class to the benchmark.
Examples:
>>> from SRToolkit.dataset import Feynman
>>> benchmark = Feynman() # Feynman is a specific instance of SR_benchmark with additional functionality
>>> dataset = benchmark.create_dataset('I.16.6')
>>> isinstance(dataset, SR_dataset)
True
>>> bm = SR_benchmark("BM")
>>> bm.add_dataset_instance("I.16.6", dataset)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
The name of the dataset. |
required |
dataset
|
SR_dataset
|
An instance of the SR_dataset class. |
required |
Raises:
| Type | Description |
|---|---|
Exception
|
If the dataset name already exists in the benchmark. |
Source code in SRToolkit/dataset/sr_benchmark.py
add_dataset
add_dataset(symbol_library: SymbolLibrary, dataset: Optional[Union[ndarray, Tuple[ndarray, ndarray]]] = None, dataset_name: Optional[str] = None, ranking_function: str = 'rmse', 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, samplers: Optional[List[Sampler]] = None, data_source: Optional[DataSource] = None, **kwargs: Unpack[EstimationSettings])
Adds a dataset to the benchmark.
Examples:
>>> import tempfile, numpy as np
>>> from SRToolkit.utils import SymbolLibrary
>>> bm = SR_benchmark("BM")
>>> X = np.random.rand(10, 2)
>>> y = X[:, 0] + X[:, 1]
>>> bm.add_dataset(SymbolLibrary.default_symbols(2),(X, y),dataset_name="test_ds",ground_truth=["X_0", "+", "X_1"],original_equation="y = x0 + x1")
>>> len(bm.list_datasets(verbose=False))
1
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
Optional[Union[ndarray, Tuple[ndarray, ndarray]]]
|
Direct data for the dataset: a 2-D numpy array (features) or a
|
None
|
symbol_library
|
SymbolLibrary
|
The symbol library to use. |
required |
dataset_name
|
Optional[str]
|
The name of the dataset. Auto-generated if |
None
|
ranking_function
|
str
|
|
'rmse'
|
max_evaluations
|
int
|
Maximum expressions to evaluate. |
-1
|
ground_truth
|
Optional[Union[List[str], Node, ndarray]]
|
Ground truth expression. |
None
|
original_equation
|
Optional[str]
|
Human-readable equation string. |
None
|
success_threshold
|
Optional[float]
|
Error threshold for success. |
None
|
seed
|
Optional[int]
|
Random seed. |
None
|
dataset_metadata
|
Optional[dict]
|
Optional dataset-level metadata dict. |
None
|
samplers
|
Optional[List[Sampler]]
|
Optional list of samplers (one per input variable). They define the problem's input distribution and power resample; a SampleSource draws from them. |
None
|
data_source
|
Optional[DataSource]
|
Optional DataSource
describing where the data comes from
(UrlSource or
SampleSource). When provided,
the |
None
|
**kwargs
|
Unpack[EstimationSettings]
|
Estimation settings forwarded to SR_evaluator. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Various validation errors (see below). |
Source code in SRToolkit/dataset/sr_benchmark.py
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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
add_from_samplers
add_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', dataset_name: Optional[str] = None, original_equation: Optional[str] = None, success_threshold: Optional[float] = None, max_evaluations: int = -1, dataset_metadata: Optional[dict] = None, **kwargs: Unpack[EstimationSettings]) -> None
Add a dataset described only by a ground-truth expression and per-variable samplers.
This is the benchmark-level counterpart to
SR_dataset.from_samplers:
it attaches a SampleSource so the data
is generated lazily from samplers (and, for RMSE, ground_truth) the first
time the dataset is materialised via
create_dataset.
Examples:
>>> from SRToolkit.dataset.sampling import UniformSampling
>>> bm = SR_benchmark("BM")
>>> bm.add_from_samplers(["X_0", "+", "X_1"],
... [UniformSampling(0, 5), UniformSampling(0, 5)], dataset_name="add",
... n_samples=100, seed=0)
>>> ds = bm.create_dataset("add")
>>> ds.X.shape
(100, 2)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ground_truth
|
Union[List[str], Node]
|
Ground-truth expression as a token list or Node. |
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 on materialisation. Defaults to |
10000
|
seed
|
Optional[int]
|
Random seed stored on the SampleSource. |
None
|
ranking_function
|
str
|
|
'rmse'
|
dataset_name
|
Optional[str]
|
Name of the dataset. Auto-generated if |
None
|
original_equation
|
Optional[str]
|
Human-readable equation string. Auto-filled from a token-list
|
None
|
success_threshold
|
Optional[float]
|
Error threshold for success. |
None
|
max_evaluations
|
int
|
Maximum expressions to evaluate. |
-1
|
dataset_metadata
|
Optional[dict]
|
Optional dataset-level metadata dict. |
None
|
**kwargs
|
Unpack[EstimationSettings]
|
Estimation settings forwarded to SR_evaluator. |
{}
|
Source code in SRToolkit/dataset/sr_benchmark.py
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | |
create_dataset
create_dataset(dataset_name: str, n_samples: Optional[int] = None, seed: Optional[int] = None) -> SR_dataset
Creates an instance of a dataset from the given dataset name.
When n_samples is provided the returned dataset contains freshly sampled data
instead of the pre-generated data on disk. The dataset must have samplers defined
(see samplers argument of
add_dataset).
Examples:
>>> from SRToolkit.dataset import Feynman
>>> benchmark = Feynman() # Feynman is a specific instance of SR_benchmark with additional functionality
>>> dataset = benchmark.create_dataset('I.16.6')
>>> dataset.X.shape
(10000, 3)
>>> dataset_small = benchmark.create_dataset('I.16.6', n_samples=500, seed=0)
>>> dataset_small.X.shape
(500, 3)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
The name of the dataset to create. |
required |
n_samples
|
Optional[int]
|
If provided, generate a fresh dataset with this many samples using the stored samplers instead of loading pre-generated data from disk. |
None
|
seed
|
Optional[int]
|
Random seed used when |
None
|
Returns:
| Type | Description |
|---|---|
SR_dataset
|
An SR_dataset instance containing the |
SR_dataset
|
data, ground truth expression, and metadata for the given dataset. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset name is not found, or if |
Source code in SRToolkit/dataset/sr_benchmark.py
list_datasets
Lists the available datasets.
Examples:
>>> from SRToolkit.dataset import Feynman
>>> benchmark = Feynman() # Feynman is a specific instance of SR_benchmark with additional functionality
>>> len(benchmark.list_datasets(num_variables=2, verbose=False))
15
>>> datasets_with_8_vars = benchmark.list_datasets(num_variables=8, verbose=False)
>>> datasets_with_8_vars[0]
'II.36.38'
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose
|
bool
|
If |
True
|
num_variables
|
int
|
If not |
-1
|
Returns:
| Type | Description |
|---|---|
List[str]
|
A list of dataset names. |
Source code in SRToolkit/dataset/sr_benchmark.py
to_dict
Serialise the benchmark to a pure JSON-safe dictionary.
Dataset entries that have an sr_dataset key (added via
add_dataset_instance)
are serialised via SR_dataset.to_dict().
Returns:
| Type | Description |
|---|---|
dict
|
A JSON-safe dict representing the full benchmark configuration. |
Source code in SRToolkit/dataset/sr_benchmark.py
from_dict
classmethod
Reconstruct an SR_benchmark from a config dict or a saved JSON file.
To load a self-contained .zip archive (written by
to_archive) use
from_archive instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
Union[dict, str, Path]
|
A dict produced by to_dict, or a path to a JSON file. |
required |
Returns:
| Type | Description |
|---|---|
SR_benchmark
|
An SR_benchmark instance. |
Source code in SRToolkit/dataset/sr_benchmark.py
to_archive
Write the benchmark (config + data) to a .zip archive.
The archive contains:
benchmark.json: the benchmark configuration dict.data/<dataset_name>.npz: the cached data for each dataset.data/<dataset_name>_gt.npy: ground-truth behaviour array (if present).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Destination path for the archive. Non- |
required |
Source code in SRToolkit/dataset/sr_benchmark.py
from_archive
classmethod
Load a benchmark from a self-contained .zip archive.
This is the counterpart to
to_archive: it reads
benchmark.json from the archive, extracts the bundled data/*.npz (and any
_gt.npy) into the data cache, and returns a benchmark whose datasets read
from that populated cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Path to a |
required |
Returns:
| Type | Description |
|---|---|
SR_benchmark
|
An SR_benchmark instance. |
Source code in SRToolkit/dataset/sr_benchmark.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
benchmark.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_benchmark
|
An SR_benchmark instance. |
Source code in SRToolkit/dataset/sr_benchmark.py
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 |
Source code in SRToolkit/dataset/sr_dataset.py
SRSD_Feynman
Bases: SR_benchmark
The SRSD Feynman symbolic regression benchmark.
Contains 120 physics equations from the Feynman Symbolic Regression Dataset with per-variable sampling strategies (log-uniform, linear, or integer with sign constraints). Data is generated on first instantiation and cached as .npz files for subsequent use.
References
Examples:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
Number of samples to generate per dataset when |
10000
|
seed
|
Optional[int]
|
Random seed used for data generation. |
42
|
force_generate
|
bool
|
If |
False
|