flexcv.interface
This module contains the CrossValidation class. This class is the central interface to interact with flexcv
.
flexcv.interface.CrossValidation
dataclass
This class is the central interface to interact with flexcv
.
Use this dataclass to configure your cross validation run with it's set_***()
methods.
You can use method chaining to set multiple configurations at once.
This allows you to provide extensive configuration with few lines of code.
It also helps you to log the configuration and results to Neptune.
Example
>>> import flexcv
>>> import neptune
>>> X = pd.DataFrame({"x": [1, 2, 3, 4, 5], "z": [1, 2, 3, 4, 5]})
>>> y = pd.Series([1, 2, 3, 4, 5])
>>> mapping = flexcv.ModelMappingDict(
... {
... "LinearModel": flexcv.ModelConfigDict(
... {
... "model": "LinearRegression",
... "kwargs": {"fit_intercept": True},
... }
... ),
... }
... )
>>> run = neptune.init_run()
>>> cv = CrossValidation()
>>> results = (
... cv
... .with_data(X, y)
... .with_models(mapping)
... .log(run)
... .perform()
... .get_results()
... )
Methods:
Name | Description |
---|---|
set_data |
Sets the data for cross validation. Pass your dataframes and series here. |
set_splits |
Sets the cross validation strategy for inner and outer folds. You may need to import |
set_models |
Sets the models to be cross validated. Pass hyperparameter distributions for model tuning here. You may need to import |
set_inner_cv |
Sets the inner cross validation configuration. Pass arguments regarding the hyperparameter optimization process. |
set_mixed_effects |
Sets the mixed effects parameters. Control if mixed effects are modeled and set arguments regarding the Expectation Maximization algorithm. |
set_run |
Sets the run parameters. Pass your Neptune run object here. |
perform |
Performs cross validation. Just call this method without args to trigger the nested cross validation run. |
Returns:
Type | Description |
---|---|
CrossValidation
|
CrossValidation object. |
Source code in flexcv/interface.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 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 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 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 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 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 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 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 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 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 |
|
flexcv.interface.CrossValidation.cv_description: str
property
Returns a string describing the cross validation configuration.
flexcv.interface.CrossValidation.results: CrossValidationResults
property
Returns a CrossValidationResults
object. This results object is a wrapper class around the results dict from the cross_validate
function.
flexcv.interface.CrossValidation.was_logged: bool
property
Returns True if the cross validation was logged.
flexcv.interface.CrossValidation.was_performed: bool
property
Returns True if the cross validation was performed.
flexcv.interface.CrossValidation.add_model(model_class, requires_inner_cv=False, model_name='', post_processor=None, params=None, callbacks=None, model_kwargs=None, fit_kwargs=None, **kwargs)
Add a model to the model mapping dict. This method is a convenience method to add a model to the model mapping dict without needing the ModelMappingDict and ModelConfigDict classes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_class |
object
|
The model class. Must have a fit() method. |
required |
requires_inner_cv |
bool
|
Whether or not the model requires inner cross validation. (Default value = False) |
False
|
model_name |
str
|
The name of the model. Used for logging. |
''
|
post_processor |
ModelPostProcessor
|
A post processor to be applied to the model. (Default value = None) |
None
|
callbacks |
Optional[Sequence[TrainingCallback]]
|
Callbacks to be passed to the fit method of the model in outer CV. (Default value = None) |
None
|
kwargs |
A dict of additional keyword arguments that will be passed to the model constructor. |
{}
|
|
fit_kwargs |
dict
|
A dict of keyword arguments that will be passed to the model fit method. |
None
|
**kwargs |
Arbitrary keyword arguments that will be passed to the ModelConfigDict. |
{}
|
Returns:
Type | Description |
---|---|
CrossValidation
|
self |
Example
>>> from flexcv import CrossValidation
>>> from flexcv.models import LinearModel
>>> cv = CrossValidation()
>>> cv.add_model(LinearModel, model_name="LinearModel", skip_inner_cv=True)
>>> from flexcv import CrossValidation
>>> from flexcv.models import LinearModel
>>> from flexcv.model_mapping import ModelMappingDict, ModelConfigDict
>>> cv = CrossValidation()
>>> mapping = ModelMappingDict(
... {
... "LinearModel": ModelConfigDict(
... {
... "model": LinearModel,
... "skip_inner_cv": True,
... }
... ),
... }
... )
>>> cv.set_models(mapping)
add_model()
method is a convenience method to add a model to the model mapping dict without needing the ModelMappingDict and ModelConfigDict classes.
In cases of multiple models per run, or if you want to reuse the model mapping dict, you should look into the ModelMappingDict
and the set_models()
method.
Source code in flexcv/interface.py
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 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 |
|
flexcv.interface.CrossValidation.get_results()
Returns a CrossValidationResults
object. This results object is a wrapper class around the results dict from the cross_validate
function.
Source code in flexcv/interface.py
flexcv.interface.CrossValidation.perform()
Perform the cross validation according to the configuration passed by the user.
Checks if a neptune run object has been set. If the user did not provide a neptune run object, a dummy run is instantiated.
All logs and plots will be logged to the dummy run and will be lost.
However, the cross validation results is created and can be returned via the CrossValidation.results
property.
Returns:
Type | Description |
---|---|
CrossValidation
|
self |
Source code in flexcv/interface.py
flexcv.interface.CrossValidation.set_data(X, y, groups=None, slopes=None, target_name='', dataset_name='')
Set the data for cross validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
DataFrame
|
The features. Must not contain the target or groups. |
required |
y |
DataFrame | Series
|
The target variable. |
required |
groups |
DataFrame | Series
|
The grouping/clustering variable. (Default value = None) |
None
|
slopes |
DataFrame | Series
|
The random slopes variable(s) (Default value = None) |
None
|
target_name |
str
|
Customize the target's name. This string will be used in logging. (Default value = "") |
''
|
dataset_name |
str
|
Customize your datasdet's name. This string will be used in logging. (Default value = "") |
''
|
Returns:
Type | Description |
---|---|
CrossValidation
|
self |
Example
Source code in flexcv/interface.py
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 |
|
flexcv.interface.CrossValidation.set_inner_cv(n_trials=100, objective_scorer=None)
Configure parameters regarding inner cross validation and Optuna optimization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_trials |
int
|
Number of trials to sample from the parameter distributions (Default value = 100) |
100
|
objective_scorer |
ObjectiveScorer
|
Callable to provide the optimization objective value. Is called during Optuna SearchCV (Default value = None) |
None
|
Returns:
Type | Description |
---|---|
CrossValidation
|
self |
Source code in flexcv/interface.py
flexcv.interface.CrossValidation.set_lmer(predict_known_groups_lmm=True)
Configure parameters regarding linear mixed effects regression models.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predict_known_groups_lmm |
bool
|
For use with LMER, whether or not known groups should be predicted (Default value = True) |
True
|
Returns:
Type | Description |
---|---|
CrossValidation
|
self |
Source code in flexcv/interface.py
flexcv.interface.CrossValidation.set_merf(add_merf_global=False, em_max_iterations=100, em_stopping_threshold=None, em_stopping_window=None)
Configure mixed effects parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
add_merf_global |
bool
|
If True, the model is passed into the MERF class after it is evaluated, to obtain mixed effects corrected predictions. (Default value = False) |
False
|
em_max_iterations |
int
|
For use with EM. Max number of iterations (Default value = 100) |
100
|
em_stopping_threshold |
float
|
For use with EM. Threshold of GLL residuals for early stopping (Default value = None) |
None
|
em_stopping_window |
int
|
For use with EM. Number of consecutive iterations to be below threshold for early stopping (Default value = None) |
None
|
Returns:
Type | Description |
---|---|
CrossValidation
|
self |
Source code in flexcv/interface.py
flexcv.interface.CrossValidation.set_models(mapping=None, yaml_path=None, yaml_string=None)
Set your models and related parameters. Pass a ModelMappingDict or pass yaml code or a path to a yaml file. The mapping attribute of the class is a ModelMappingDict that contains a ModelConfigDict for each model. The class attribute self.config["mapping"] is always updated in this method. Therefore, you can call this method multiple times to add models to the mapping. You can also call set_models() with a ModelMappingDict and then call set_models() again with yaml code or a path to a yaml file or after you already called add_models().
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mapping |
ModelMappingDict[str, ModelConfigDict]
|
Dict of model names and model configurations. See ModelMappingDict for more information. (Default value = None) |
None
|
yaml_path |
str | Path
|
Path to a yaml file containing a model mapping. See flexcv.yaml_parser for more information. (Default value = None) |
None
|
yaml_string |
str
|
String containing yaml code. See flexcv.yaml_parser for more information. (Default value = None) |
None
|
Returns:
Type | Description |
---|---|
CrossValidation
|
self |
Example
In your yaml file:
In your code: This will automatically read the yaml file and create a ModelMappingDict. It even takes care of the imports and instantiates the classes of model, postprocessor and for the optune distributions.Source code in flexcv/interface.py
flexcv.interface.CrossValidation.set_run(run=None, diagnostics=False, random_seed=42)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
run |
Run
|
The run object to use for logging (Default value = None) |
None
|
diagnostics |
bool
|
If True, extended diagnostic plots are logged (Default value = False) |
False
|
random_seed |
int
|
Seed for random processes (Default value = 42) |
42
|
Returns:
Type | Description |
---|---|
CrossValidation
|
self |
Source code in flexcv/interface.py
flexcv.interface.CrossValidation.set_splits(split_out=CrossValMethod.KFOLD, split_in=CrossValMethod.KFOLD, n_splits_out=5, n_splits_in=5, scale_out=True, scale_in=True, break_cross_val=False, metrics=None)
Set the cross validation strategy.
Set the split method simply by passing the CrossValMethod
as a string or enum value. Passing as string might be more convenient for you but could lead to typos.
When passing as string, the string must be a valid value of the CrossValMethod
enum.
See the reference for CrossValMethod
for more details.
Valid strings for split_out
and split_in
:
- "KFold"
- "StratifiedKFold"
- "CustomStratifiedKFold"
- "GroupKFold"
- "StratifiedGroupKFold"
- "CustomStratifiedGroupKFold"
Parameters:
Name | Type | Description | Default |
---|---|---|---|
split_out |
str | CrossValMethod
|
Outer split method. (Default value = CrossValMethod.KFOLD) |
KFOLD
|
split_in |
str | CrossValMethod
|
Inner split method for hyperparameter tuning. (Default value = CrossValMethod.KFOLD) |
KFOLD
|
n_splits_out |
int
|
Number of splits in outer loop. (Default value = 5) |
5
|
n_splits_in |
int
|
Number of splits in inner loop. (Default value = 5) |
5
|
scale_out |
bool
|
Whether or not the Features of the outer loop will be scaled to mean 0 and variance 1. (Default value = True) |
True
|
scale_in |
bool
|
Whether or not the Features of the inner loop will be scaled to mean 0 and variance 1. (Default value = True) |
True
|
break_cross_val |
bool
|
If True, the outer loop we break after first iteration. Use for debugging. (Default value = False) |
False
|
metrics |
MetricsDict
|
A dict containing evaluation metrics for the outer loop results. See MetricsDict for details. (Default value = None) |
None
|
Returns:
Type | Description |
---|---|
CrossValidation
|
self |
Example
Passing the method as instance of CrossValMethod:
Passing the method as a string:Split methods
The split strategy is controlled by the split_out
and split_in
arguments. You can pass the actual CrossValMethod
enum or a string.
The split_out
argument controls the fold assignment in the outer cross validation loop.
In each outer loop the model is fit on the training fold and model performance is evaluated on unseen data of the test fold.
The split_in
argument controls the inner loop split strategy. The inner loop cross validates the hyperparameters of the model.
A model is typically built by sampling from a distribution of hyperparameters. It is fit on the inner training fold and evaluated on the inner test fold.
Of course, the inner loop is nested in the outer loop, so the inner split is performed on the outer training fold.
Read more about it in the respective documentation of the CrossValMethod
enum.
Source code in flexcv/interface.py
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 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 |
|