|
| 1 | +import lightning as L |
| 2 | +from spotPython.data.lightcrossvalidationdatamodule import LightCrossValidationDataModule |
| 3 | +from spotPython.utils.eda import generate_config_id |
| 4 | +from pytorch_lightning.loggers import TensorBoardLogger |
| 5 | +from lightning.pytorch.callbacks.early_stopping import EarlyStopping |
| 6 | +from spotPython.torch.initialization import kaiming_init, xavier_init |
| 7 | +import os |
| 8 | + |
| 9 | + |
| 10 | +def cv_model(config: dict, fun_control: dict) -> float: |
| 11 | + """ |
| 12 | + Performs k-fold cross-validation on a model using the given configuration and function control parameters. |
| 13 | +
|
| 14 | + Args: |
| 15 | + config (dict): A dictionary containing the configuration parameters for the model. |
| 16 | + fun_control (dict): A dictionary containing the function control parameters. |
| 17 | +
|
| 18 | + Returns: |
| 19 | + (float): The mean average precision at k (MAP@k) score of the model. |
| 20 | +
|
| 21 | + Examples: |
| 22 | + >>> config = { |
| 23 | + ... "initialization": "Xavier", |
| 24 | + ... "batch_size": 32, |
| 25 | + ... "patience": 10, |
| 26 | + ... } |
| 27 | + >>> fun_control = { |
| 28 | + ... "_L_in": 10, |
| 29 | + ... "_L_out": 1, |
| 30 | + ... "enable_progress_bar": True, |
| 31 | + ... "core_model": MyModel, |
| 32 | + ... "num_workers": 4, |
| 33 | + ... "DATASET_PATH": "./data", |
| 34 | + ... "CHECKPOINT_PATH": "./checkpoints", |
| 35 | + ... "TENSORBOARD_PATH": "./tensorboard", |
| 36 | + ... "k_folds": 5, |
| 37 | + ... } |
| 38 | + >>> mapk_score = cv_model(config, fun_control) |
| 39 | + """ |
| 40 | + _L_in = fun_control["_L_in"] |
| 41 | + _L_out = fun_control["_L_out"] |
| 42 | + if fun_control["enable_progress_bar"] is None: |
| 43 | + enable_progress_bar = False |
| 44 | + else: |
| 45 | + enable_progress_bar = fun_control["enable_progress_bar"] |
| 46 | + # Add "CV" postfix to config_id |
| 47 | + config_id = generate_config_id(config) + "_CV" |
| 48 | + results = [] |
| 49 | + num_folds = fun_control["k_folds"] |
| 50 | + split_seed = 12345 |
| 51 | + |
| 52 | + for k in range(num_folds): |
| 53 | + print("k:", k) |
| 54 | + |
| 55 | + model = fun_control["core_model"](**config, _L_in=_L_in, _L_out=_L_out) |
| 56 | + initialization = config["initialization"] |
| 57 | + if initialization == "Xavier": |
| 58 | + xavier_init(model) |
| 59 | + elif initialization == "Kaiming": |
| 60 | + kaiming_init(model) |
| 61 | + else: |
| 62 | + pass |
| 63 | + # print(f"model: {model}") |
| 64 | + |
| 65 | + dm = LightCrossValidationDataModule( |
| 66 | + k=k, |
| 67 | + num_splits=num_folds, |
| 68 | + split_seed=split_seed, |
| 69 | + dataset=fun_control["data_set"], |
| 70 | + num_workers=fun_control["num_workers"], |
| 71 | + batch_size=config["batch_size"], |
| 72 | + data_dir=fun_control["DATASET_PATH"], |
| 73 | + ) |
| 74 | + dm.prepare_data() |
| 75 | + dm.setup() |
| 76 | + |
| 77 | + # Init trainer |
| 78 | + trainer = L.Trainer( |
| 79 | + # Where to save models |
| 80 | + default_root_dir=os.path.join(fun_control["CHECKPOINT_PATH"], config_id), |
| 81 | + max_epochs=model.hparams.epochs, |
| 82 | + accelerator="auto", |
| 83 | + devices=1, |
| 84 | + logger=TensorBoardLogger( |
| 85 | + save_dir=fun_control["TENSORBOARD_PATH"], version=config_id, default_hp_metric=True, log_graph=True |
| 86 | + ), |
| 87 | + callbacks=[ |
| 88 | + EarlyStopping(monitor="val_loss", patience=config["patience"], mode="min", strict=False, verbose=False) |
| 89 | + ], |
| 90 | + enable_progress_bar=enable_progress_bar, |
| 91 | + ) |
| 92 | + # Pass the datamodule as arg to trainer.fit to override model hooks :) |
| 93 | + trainer.fit(model=model, datamodule=dm) |
| 94 | + # Test best model on validation and test set |
| 95 | + # result = trainer.validate(model=model, datamodule=dm, ckpt_path="last") |
| 96 | + score = trainer.validate(model=model, datamodule=dm) |
| 97 | + # unlist the result (from a list of one dict) |
| 98 | + score = score[0] |
| 99 | + print(f"train_model result: {score}") |
| 100 | + |
| 101 | + results.append(score["val_loss"]) |
| 102 | + |
| 103 | + score = sum(results) / num_folds |
| 104 | + # print(f"cv_model mapk result: {mapk_score}") |
| 105 | + return score |
0 commit comments