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. |
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).
For more information about the Feynman benchmark, see: https://doi.org/10.1126/sciadv.aay2631
Examples:
>>> benchmark = Feynman()
>>> len(benchmark.list_datasets(verbose=False))
100
>>> X, y = benchmark.resample('I.16.6', n=500, seed=0)
>>> X.shape
(500, 3)
>>> y.shape
(500,)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_directory
|
str
|
Directory where dataset files are stored or will be downloaded to.
Defaults to the platform-appropriate user data directory (e.g. |
join(user_data_dir('SRToolkit'), 'feynman')
|
Source code in SRToolkit/dataset/feynman.py
resample
Generate fresh data for a dataset by sampling new inputs and evaluating the ground truth.
Variable bounds are taken from _BOUNDS.
Examples:
>>> benchmark = Feynman()
>>> X, y = benchmark.resample('I.16.6', n=200, seed=42)
>>> X.shape
(200, 3)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
Name of the dataset to resample. |
required |
n
|
int
|
Number of new samples to generate. |
required |
seed
|
Optional[int]
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
A tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset has no ground truth expression. |
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.
For more information about the Nguyen benchmark, see: https://doi.org/10.1007/s10710-010-9121-2
Examples:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_directory
|
str
|
Directory where dataset files are stored or will be downloaded to.
Defaults to the platform-appropriate user data directory (e.g. |
join(user_data_dir('SRToolkit'), 'nguyen')
|
Source code in SRToolkit/dataset/nguyen.py
resample
Generate fresh data for a dataset by sampling new inputs and evaluating the ground truth.
Variable bounds are taken from _BOUNDS.
Examples:
>>> benchmark = Nguyen('data/nguyen/')
>>> X, y = benchmark.resample('NG-1', n=200, seed=42)
>>> X.shape
(200, 1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
Name of the dataset to resample. |
required |
n
|
int
|
Number of new samples to generate. |
required |
seed
|
Optional[int]
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
A tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset has no ground truth expression. |
Source code in SRToolkit/dataset/nguyen.py
SR_benchmark
SR_benchmark(
benchmark_name: str,
base_dir: str,
datasets: Optional[List[Union[SR_dataset, Tuple[str, SR_dataset]]]] = None,
metadata: Optional[Dict[str, Any]] = 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 |
base_dir
|
str
|
Directory where dataset files are stored or will be written. |
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
|
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", "data/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(
dataset: Union[str, ndarray, Tuple[ndarray, ndarray]],
symbol_library: SymbolLibrary,
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,
**kwargs: Unpack[EstimationSettings],
)
Adds a dataset to the benchmark.
Examples:
>>> from SRToolkit.dataset import Feynman
>>> fey_benchmark = Feynman() # Feynman is a specific instance of SR_benchmark with additional functionality
>>> benchmark = SR_benchmark("BM", "data/bm")
>>> benchmark.add_dataset(fey_benchmark.base_dir+"/I.14.3.npz", SymbolLibrary.default_symbols(3),
... dataset_name="I.14.3", ranking_function="rmse", ground_truth = ["X_0", "*", "X_1", "*", "X_2"],
... original_equation="U = m*g*z", max_evaluations=100000, max_expr_length=50,
... success_threshold=1e-7, dataset_metadata={}, constant_bounds=(-5.0, 5.0),
... seed = 42)
>>> len(benchmark.list_datasets(verbose=False))
1
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
Union[str, ndarray, Tuple[ndarray, ndarray]]
|
Data used in the dataset. Can be: - A string representing the path to a NumPy archive (.npz) containing the dataset. It should either the absolute path to the data, path relative to the base_dir 'base_dir'/'dataset', or empty, in that case the dataset will be loaded from 'base_dir'/'dataset_name'.npz. The .npz file must contain the features (saved in 'X') and if 'rmse' is used as the ranking function, the target (saved in 'y'). - A 2d numpy array containing the features (X). If 'rmse' is used as the ranking function, ground truth should also be provided to calculate the target (y). Once added, the data will be saved at 'base_dir'/'dataset_name'.npz. - A tuple containing the features (X) and the target (y). If 'bed' is used as the ranking function, the target will be ignored. Once added, the data will be saved at 'base_dir'/'dataset_name'.npz. |
required |
symbol_library
|
SymbolLibrary
|
The symbol library to use. |
required |
dataset_name
|
Optional[str]
|
The name of the dataset. If None, a name will be generated automatically as 'benchmark_name'_'index+1'. |
None
|
ranking_function
|
str
|
The ranking function used during evaluation. Can be: 'rmse', 'bed'. |
'rmse'
|
max_evaluations
|
int
|
The maximum number of expressions to evaluate. Less than 0 means no limit. |
-1
|
ground_truth
|
Optional[Union[List[str], Node, ndarray]]
|
Ground truth expression as a token list in infix notation, a
Node tree, or a numpy behavior array. Required when
|
None
|
original_equation
|
Optional[str]
|
Human-readable string of the original equation. |
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 dataset-level metadata (merged with benchmark metadata). |
None
|
**kwargs
|
Unpack[EstimationSettings]
|
Optional estimation settings passed to
SR_evaluator.
Supported keys: |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When BED ranking function is used but ground truth is not provided. When dataset is given as a string (directory) that doesn't exist, is not a valid .npz file, or is a .npz file that doesn't contain one array for the BED ranking function (X) or two array for the RMSE ranking function (X, y). When the argument dataset is an array, ranking function RMSE and there is no ground truth or the expression given as the ground truth cannot be evaluated... |
Source code in SRToolkit/dataset/sr_benchmark.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 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 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 300 301 302 303 304 305 306 | |
create_dataset
Creates an instance of a dataset from the given dataset name.
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)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
The name of the dataset to create. |
required |
Returns:
| Type | Description |
|---|---|
SR_dataset
|
A SR_dataset instance containing the data, ground truth expression, and metadata for the given dataset. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset name is not found in the available datasets. |
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
save_benchmark
Saves the benchmark to <base_dir>/dataset_info.json.
The JSON file stores dataset metadata and paths to data files; the data arrays themselves are not embedded. Use load_benchmark to restore the benchmark.
Examples:
>>> from SRToolkit.dataset import Feynman
>>> benchmark = Feynman() # Feynman is a specific instance of SR_benchmark with additional functionality
>>> benchmark.save_benchmark()
Source code in SRToolkit/dataset/sr_benchmark.py
load_benchmark
staticmethod
Loads a benchmark stored at the base directory, returning an instance of SR_benchmark.
Examples:
>>> from SRToolkit.dataset import Feynman
>>> b1 = Feynman("data/feynman") # Feynman is a specific instance of SR_benchmark with additional functionality
>>> b1.save_benchmark()
>>> b2 = SR_benchmark.load_benchmark('data/feynman')
>>> len(b1.list_datasets(verbose=False))
100
>>> len(b2.list_datasets(verbose=False))
100
>>> dataset_name = b2.list_datasets(verbose=False)[0]
>>> dataset = b2.create_dataset(dataset_name)
>>> rmse = dataset.create_evaluator().evaluate_expr(dataset.ground_truth)
>>> bool(rmse < dataset.success_threshold)
True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_dir
|
str
|
Directory containing the |
required |
Returns:
| Type | Description |
|---|---|
SR_benchmark
|
An SR_benchmark instance with all datasets restored from the saved JSON. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
JSONDecodeError
|
If the JSON file is malformed. |
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",
**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 token vocabulary. |
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 vectors (see create_behavior_matrix). |
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'
|
**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
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 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 | |
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
to_dict
Creates a dictionary representation of this dataset. This is mainly used for saving the dataset to disk.
Examples:
>>> import tempfile
>>> 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)
>>> dataset.to_dict("data/example_ds")
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_path
|
str
|
The path to the directory where the data in the dataset should be saved. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary representation of this dataset. |
Source code in SRToolkit/dataset/sr_dataset.py
from_dict
staticmethod
Creates an instance of the SR_dataset class from its dictionary representation. This is mainly used for loading the dataset from disk.
Examples:
>>> import tempfile, os
>>> tmpdir = tempfile.mkdtemp()
>>> X = np.array([[1, 2], [3, 4], [5, 6]])
>>> ds = 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)
>>> dataset_dict = ds.to_dict(tmpdir)
>>> dataset = SR_dataset.from_dict(dataset_dict)
>>> dataset.X.shape
(3, 2)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
Dictionary representation of the dataset, as produced by to_dict. |
required |
Returns:
| Type | Description |
|---|---|
SR_dataset
|
A new SR_dataset instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the |
Exception
|
If the dataset file or ground truth file cannot be loaded. |