SR Evaluator
            SRToolkit.evaluation.sr_evaluator
    This module contains the SR_evaluator class, which is used for evaluating symbolic regression approaches. Additionally, the generic ResultAugmenter class is defined here to avoid circular imports.
            ResultAugmenter
    Generic class that defines the interface for result augmentation. For examples, see the implementations of this class.
Source code in SRToolkit/evaluation/sr_evaluator.py
                    
                  
            augment_results
    Augments the results dictionary with additional information. The model variable contains all models, for only top models, results["top_models"] should be used.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
                results
             | 
            
                  dict
             | 
            
               The dictionary containing the results to augment.  | 
            required | 
                models
             | 
            
                  List[dict]
             | 
            
               A list of dictionaries describing the performance of expressions using the base ranking function. Keyword expr contains the expression, error contains the error of the expression. The list is sorted by error.  | 
            required | 
                evaluator
             | 
            
                  SR_evaluator
             | 
            
               The evaluator used to evaluate the models.  | 
            required | 
Returns:
| Type | Description | 
|---|---|
                  dict
             | 
            
               The augmented results dictionary.  | 
          
Source code in SRToolkit/evaluation/sr_evaluator.py
              
            to_dict
    Transforms the augmenter into a dictionary. This is used for saving the augmenter to disk.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
                base_path
             | 
            
                  str
             | 
            
               The base path used for saving the data inside the augmenter, if needed.  | 
            required | 
                name
             | 
            
                  str
             | 
            
               The name/identifier used by the augmenter for saving.  | 
            required | 
Returns:
| Type | Description | 
|---|---|
                  dict
             | 
            
               A dictionary containing the necessary information to recreate the augmenter.  | 
          
Source code in SRToolkit/evaluation/sr_evaluator.py
              
            from_dict
  
      staticmethod
  
    Creates an instance of the ResultAugmenter class from the dictionary with the relevant data.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
                data
             | 
            
                  dict
             | 
            
               the dictionary containing the data needed to recreate the augmenter.  | 
            required | 
                augmenter_map
             | 
            
                  Optional[dict]
             | 
            
               A dictionary mapping augmenter names to their classes.  | 
            
                  None
             | 
          
Returns:
| Type | Description | 
|---|---|
                  ResultAugmenter
             | 
            
               An instance of the ResultAugmenter class with the same configuration as in the data dictionary.  | 
          
Source code in SRToolkit/evaluation/sr_evaluator.py
              
            SR_evaluator
SR_evaluator(X: ndarray, y: Optional[ndarray] = None, symbol_library: SymbolLibrary = SymbolLibrary.default_symbols(), max_evaluations: int = -1, success_threshold: Optional[float] = None, ranking_function: str = 'rmse', ground_truth: Optional[Union[List[str], Node, ndarray]] = None, result_augmenters: Optional[List[ResultAugmenter]] = None, seed: Optional[int] = None, metadata: Optional[dict] = None, **kwargs)
Initializes an instance of the SR_evaluator class. This class is used for evaluating symbolic regression approaches.
Examples:
>>> X = np.array([[1, 2], [8, 4], [5, 4], [7, 9], ])
>>> y = np.array([3, 0, 3, 11])
>>> se = SR_evaluator(X, y)
>>> rmse = se.evaluate_expr(["C", "*", "X_1", "-", "X_0"])
>>> print(rmse < 1e-6)
True
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
                X
             | 
            
                  ndarray
             | 
            
               The input data to be used in parameter estimation for variables. We assume that X is a 2D array with shape (n_samples, n_features).  | 
            required | 
                y
             | 
            
                  Optional[ndarray]
             | 
            
               The target values to be used in parameter estimation.  | 
            
                  None
             | 
          
                max_evaluations
             | 
            
                  int
             | 
            
               The maximum number of expressions to evaluate. Default is -1, which means no limit.  | 
            
                  -1
             | 
          
                success_threshold
             | 
            
                  Optional[float]
             | 
            
               The threshold used for determining whether an expression is considered successful. If None, the threshold is set to 1e-7 for RMSE and calculated automatically for BED. For BED we calculate this value by evaluating the distance of ground truth to itself 100 times and setting the threshold to np.max(distances)*1.1. For this calculation to be helpful, ground_truth must be provided as a list of tokens or SRToolkit.utils.Node object.  | 
            
                  None
             | 
          
                metadata
             | 
            
                  Optional[dict]
             | 
            
               An optional dictionary containing metadata about this evaluation. This could include information such as the dataset used, the model used, seed, etc.  | 
            
                  None
             | 
          
                symbol_library
             | 
            
                  SymbolLibrary
             | 
            
               The symbol library to use.  | 
            
                  default_symbols()
             | 
          
                ranking_function
             | 
            
                  str
             | 
            
               The function used for ranking the expressions and fitting parameters if needed. Currently, "rmse" and "bed" are supported. Default is "rmse".  | 
            
                  'rmse'
             | 
          
                ground_truth
             | 
            
                  Optional[Union[List[str], Node, ndarray]]
             | 
            
               The ground truth for the BED evaluation. This should be a list of tokens, a Node object, or a numpy array representing behavior (see SRToolkit.utils.create_behavior_matrix for more details).  | 
            
                  None
             | 
          
                result_augmenters
             | 
            
                  Optional[List[ResultAugmenter]]
             | 
            
               Optional list of objects that augment the results returned by the "get_results" function. For example, SRToolkit.evaluation.result_augmentation.ExpressionSimplifier simplifies the evaluated expressions. Possible augmenters can be found in SRToolkit.evaluation.result_augmentation.py or customly defined by inheriting from SRToolkit.evaluation.result_augmentation.ResultAugmenter class.  | 
            
                  None
             | 
          
                seed
             | 
            
                  Optional[int]
             | 
            
               The seed to use for random number generation.  | 
            
                  None
             | 
          
Other Parameters:
| Name | Type | Description | 
|---|---|---|
method | 
            
                  str
             | 
            
               The method to be used for minimization. Currently, only "L-BFGS-B" is supported/tested. Default is "L-BFGS-B".  | 
          
tol | 
            
                  float
             | 
            
               The tolerance for termination. Default is 1e-6.  | 
          
gtol | 
            
                  float
             | 
            
               The tolerance for the gradient norm. Default is 1e-3.  | 
          
max_iter | 
            
                  int
             | 
            
               The maximum number of iterations. Default is 100.  | 
          
constant_bounds | 
            
                  Tuple[float, float]
             | 
            
               A tuple of two elements, specifying the lower and upper bounds for the constant values. Default is (-5, 5).  | 
          
initialization | 
            
                  str
             | 
            
               The method to use for initializing the constant values. Currently, only "random" and "mean" are supported. "random" creates a vector with random values sampled within the bounds. "mean" creates a vector where all values are calculated as (lower_bound + upper_bound)/2. Default is "random".  | 
          
max_constants | 
            
                  int
             | 
            
               The maximum number of constants allowed in the expression. Default is 8.  | 
          
max_expr_length | 
            
                  int
             | 
            
               The maximum length of the expression. Default is -1 (no limit).  | 
          
num_points_sampled | 
            
                  int
             | 
            
               The number of points to sample when estimating the behavior of an expression. Default is 64. If num_points_sampled==-1, then the number of points sampled is equal to the number of points in the dataset.  | 
          
bed_X | 
            
                  Optional[ndarray]
             | 
            
               Points used for BED evaluation. If None and domain_bounds are given, points are sampled from the domain. If None and domain_bounds are not givem, points are randomly selected from X. Default is None.  | 
          
num_consts_sampled | 
            
                  int
             | 
            
               Number of constants sampled for BED evaluation. Default is 32.  | 
          
domain_bounds | 
            
                  Optional[List[Tuple[float, float]]]
             | 
            
               Bounds for the domain to be used if bed_X is None to sample random points. Default is None.  | 
          
Attributes:
| Name | Type | Description | 
|---|---|---|
models | 
            
               A dictionary containing the results of previously evaluated expressions.  | 
          |
invalid | 
            
               A list containing the expressions that could not be evaluated.  | 
          |
ground_truth | 
            
               The ground truth we are trying to find.  | 
          |
gt_behavior | 
            
               The behavior matrix for the ground truth that is used when BED is chosen as the ranking function.  | 
          |
max_evaluations | 
            
               The maximum number of expressions to evaluate.  | 
          |
bed_evaluation_parameters | 
            
               A dictionary containing parameters used for BED evaluation.  | 
          |
metadata | 
            
               An optional dictionary containing metadata about this evaluation. This could include information such as the dataset used, the model used, seed, etc.  | 
          |
symbol_library | 
            
               The symbol library to use.  | 
          |
total_evaluations | 
            
               The number of times the "evaluate_expr" function was called.  | 
          |
seed | 
            
               The seed to use for random number generation.  | 
          |
parameter_estimator | 
            
               An instance of the ParameterEstimator class used for parameter estimation.  | 
          |
ranking_function | 
            
               The function used for ranking the expressions and fitting parameters if needed.  | 
          |
success_threshold | 
            
               The threshold used for determining whether an expression is considered successful.  | 
          |
result_augmenters | 
            
               A list of SRToolkit.evaluation.result_augmentation.ResultAugmenter objects that augment the results returned by the get_results.  | 
          
Functions:
| Name | Description | 
|---|---|
evaluate_expr | 
              
                 Evaluates an expression in infix notation and stores the result in memory to prevent re-evaluation.  | 
            
get_results | 
              
                 Returns the results of the evaluation.  | 
            
Notes
Determining if two expressions are equivalent is undecidable. Furthermore, random sampling, parameter fitting, and numerical errors all make it hard to determine whether we found the correct expression. Because of this, the success threshold is only a proxy for determining the success of an expression. We recommend checking the best performing expression manually for a better indication of success.
Source code in SRToolkit/evaluation/sr_evaluator.py
                    75 76 77 78 79 80 81 82 83 84 85 86 87 88 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 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  |  | 
            evaluate_expr
    Evaluates an expression in infix notation and stores the result in memory to prevent re-evaluation.
Examples:
>>> X = np.array([[1, 2], [8, 4], [5, 4], [7, 9], ])
>>> y = np.array([3, 0, 3, 11])
>>> se = SR_evaluator(X, y)
>>> rmse = se.evaluate_expr(["C", "*", "X_1", "-", "X_0"])
>>> print(rmse < 1e-6)
True
>>> X = np.array([[0, 1], [0, 2], [0, 3]])
>>> y = np.array([2, 3, 4])
>>> se = SR_evaluator(X, y)
>>> rmse = se.evaluate_expr(["C", "+", "C" "*", "C", "+", "X_0", "*", "X_1", "/", "X_0"], simplify_expr=True)
>>> print(rmse < 1e-6)
True
>>> list(se.models.keys())[0]
'C+X_1'
>>> print(0.99 < se.models["C+X_1"]["parameters"][0] < 1.01)
True
>>> # Evaluating invalid expression returns nan and adds it to invalid list
>>> se.evaluate_expr(["C", "*", "X_1", "X_0"])
nan
>>> se.invalid
['C*X_1X_0']
>>> X = np.random.rand(10, 2) - 0.5
>>> gt = ["X_0", "+", "C"]
>>> se = SR_evaluator(X, ground_truth=gt, ranking_function="bed")
>>> se.evaluate_expr(["C", "+", "X_1"]) < 1
True
>>> # When evaluating using BED as the ranking function, the error depends on the scale of output of the
>>> # ground truth. Because of stochasticity of BED, error might be high even when expressions match exactly.
>>> se.evaluate_expr(["C", "+", "X_0"]) < 0.2
True
>>> # X can also be sampled from a domain by providing domain_bounds
>>> se = SR_evaluator(X, ground_truth=gt, ranking_function="bed", domain_bounds=[(-1, 1), (-1, 1)])
>>> se.evaluate_expr(["C", "+", "X_0"]) < 0.2
True
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
                expr
             | 
            
                  Union[List[str], Node]
             | 
            
               An expression. This should be an istance of the SRToolkit.utils.expression_tree.Node class or a list of tokens in the infix notation.  | 
            required | 
                simplify_expr
             | 
            
                  bool
             | 
            
               If True, simplifies the expression using SymPy before evaluating it. This typically slows down evaluation. We recommend simplifying only the best expressions when getting results using the get_results method.  | 
            
                  False
             | 
          
                verbose
             | 
            
                  int
             | 
            
               When 0, no additional output is printed, when 1, prints the expression being evaluated, RMSE, and estimated parameters, and when 2, also prints numpy errors produced during evaluation.  | 
            
                  0
             | 
          
Returns:
| Type | Description | 
|---|---|
                  float
             | 
            
               The root-mean-square error of the expression.  | 
          
Warns:
| Type | Description | 
|---|---|
                  Maximum number of evaluations reached
             | 
            
               If the maximum number of evaluations has been reached, a warning is printed and np.nan is returned.  | 
          
Notes
If the expression has already been evaluated, its stored value is returned instead of re-evaluating the expression. When the maximum number of evaluations has been reached, a warning is printed and np.nan is returned.
Source code in SRToolkit/evaluation/sr_evaluator.py
              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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 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  |  | 
            get_results
    Returns the results of the equation discovery/symbolic regression process/evaluation.
Examples:
>>> X = np.array([[1, 2], [8, 4], [5, 4], [7, 9], ])
>>> y = np.array([3, 0, 3, 11])
>>> se = SR_evaluator(X, y)
>>> rmse = se.evaluate_expr(["C", "*", "X_1", "-", "X_0"])
>>> results = se.get_results(top_k=1, verbose=False)
>>> print(results["num_evaluated"])
1
>>> print(results["evaluation_calls"])
1
>>> print(results["best_expr"])
C*X_1-X_0
>>> print(results["min_error"] < 1e-6)
True
>>> print(1.99 < results["top_models"][0]["parameters"][0] < 2.01)
True
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
                top_k
             | 
            
                  int
             | 
            
               The number of top results to include in the output. If   | 
            
                  20
             | 
          
                verbose
             | 
            
                  bool
             | 
            
               If True, prints the results of the evaluation.  | 
            
                  True
             | 
          
Returns:
| Type | Description | 
|---|---|
                  dict
             | 
            
               A dictionary containing the results of the equation discovery/symbolic regression process. The keys are: 
  | 
          
Source code in SRToolkit/evaluation/sr_evaluator.py
              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 526 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  |  | 
            to_dict
    Creates a dictionary representation of the SR_evaluator.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
                base_path
             | 
            
                  str
             | 
            
               Used to save the data of the evaluator to disk.  | 
            required | 
                name
             | 
            
                  str
             | 
            
               Used to save the data of the evaluator to disk.  | 
            required | 
Returns:
| Type | Description | 
|---|---|
                  dict
             | 
            
               A dictionary containing the necessary information to recreate the evaluator from disk.  | 
          
Source code in SRToolkit/evaluation/sr_evaluator.py
              
            from_dict
  
      staticmethod
  
    Creates an instance of the SR_evaluator from a dictionary.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
                data
             | 
            
                  dict
             | 
            
               A dictionary containing the necessary information to recreate the evaluator.  | 
            required | 
                augmenter_map
             | 
            
                  Optional[dict]
             | 
            
               A dictionary mapping the names of the augmenters to the augmenter classes.  | 
            
                  None
             | 
          
Returns:
| Type | Description | 
|---|---|
                  SR_evaluator
             | 
            
               An instance of the SR_evaluator.  | 
          
Raises:
| Type | Description | 
|---|---|
                  Exception
             | 
            
               if unable to load data for X/y/ground truth data, if result augmenters provided but not the augmenter map or if the result augmentor does not occur in the augmenter map.  |