model_evaluation.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import utils.ensemble as ens
  2. import os
  3. import tomli as tml
  4. from utils.system import force_init_cudnn
  5. import torch
  6. import pathlib as pl
  7. from utils.data.datasets import ADNIDataset
  8. import xarray as xr
  9. # CONFIGURATION
  10. with open(os.getenv("ADL_CONFIG_PATH", "config.toml"), "rb") as f:
  11. config = tml.load(f)
  12. force_init_cudnn(config["training"]["device"])
  13. # INIT DATA AND MODELS
  14. ensemble_folder: pl.Path = (
  15. config["paths"]["model_output"] + config["ensemble"]["name"] + "/models/"
  16. )
  17. # Load test data
  18. test_dataset: ADNIDataset = torch.load(
  19. config["paths"]["model_output"] + config["ensemble"]["name"] + "/test_dataset.pt",
  20. weights_only=False,
  21. )
  22. models = ens.load_models(pl.Path(ensemble_folder), config["training"]["device"])
  23. # We are generating a large matrix, with the dimensions of the models, the test set, and the number of classes
  24. # Therefore we are capturing the output of every model for every item in the test set and storing it in a matrix
  25. type ResultsMatrix = xr.DataArray
  26. type ActualMatrix = xr.DataArray
  27. results: ResultsMatrix = xr.DataArray(
  28. data=0,
  29. dims=["model", "test_item", "class"],
  30. coords={
  31. "model": ens.get_model_names(models),
  32. "test_item": range(len(test_dataset)),
  33. "class": [0, 1],
  34. },
  35. )
  36. actual: ActualMatrix = xr.DataArray(
  37. data=0,
  38. dims=["test_item", "class"],
  39. coords={
  40. "test_item": range(len(test_dataset)),
  41. "class": [0, 1],
  42. },
  43. )
  44. final: xr.Dataset = xr.Dataset(
  45. data_vars={
  46. "evaluated": results,
  47. "actual": actual,
  48. },
  49. )
  50. # Iterate over the test set and get the predictions for each model
  51. for i, (unp_data, target) in enumerate(test_dataset):
  52. data = ens.prepare_datasets(unp_data)
  53. for j, (model_obj, model_name) in enumerate(models):
  54. model_obj.eval()
  55. with torch.no_grad():
  56. output: torch.Tensor = model_obj(data)
  57. final.results.loc[dict(model=model_name, test_item=i)] = output.numpy() # type: ignore
  58. final.actual.loc[dict(test_item=i)] = target.numpy() # type: ignore
  59. # Save the results to a file
  60. final.to_netcdf( # type: ignore
  61. config["paths"]["model_output"] + config["ensemble"]["name"] + "/test_results.nc",
  62. mode="w",
  63. format="NETCDF4",
  64. )