predict
main(cfg)
Main entry point for evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg |
DictConfig
|
configuration composed by Hydra. |
required |
Source code in meds_torch/predict.py
predict(cfg, datamodule=None)
Evaluates given checkpoint on a datamodule testset.
This method is wrapped in optional @task_wrapper decorator, that controls the behavior during failure. Useful for multiruns, saving info about the crash, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg |
DictConfig
|
DictConfig configuration composed by Hydra. |
required |
Returns: Tuple[dict, dict] with metrics and dict with all instantiated objects.
Examples:
import tempfile from omegaconf import DictConfig _ = pl.Config.set_tbl_width_chars(106)
Create temporary checkpoint file
with tempfile.TemporaryDirectory() as tmp_dir: … ckpt_path = Path(tmp_dir) / “model.ckpt” … torch.save({“state_dict”: {}}, ckpt_path) … … # Create config … cfg = { … “seed”: 0, … “ckpt_path”: str(ckpt_path), … “model”: {“target”: “meds_torch.predict.DummyModel”}, … “data”: { … “target”: “meds_torch.predict.DummyDataModule”, … “task_name”: “test_task”, … “do_include_subject_id”: True, … “do_include_prediction_time”: True … }, … “paths”: { … “predict_fp”: str(Path(tmp_dir) / “predictions.parquet”), … “time_output_dir”: tmp_dir … }, … “trainer”: {“target”: “meds_torch.predict.DummyTrainer”}, … “logger”: None … } … cfg = DictConfig(cfg) … … # Run prediction … predict(cfg) … … # Verify outputs … assert Path(cfg.paths.predict_fp).exists() … print(pl.read_parquet(cfg.paths.predict_fp)) # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS shape: (2, 5) ┌────────────┬─────────────────────┬───────────────┬─────────────────────────┬───────────────────────────┐ │ subject_id ┆ prediction_time ┆ boolean_value ┆ predicted_boolean_value ┆ predicted_boolean_probabi │ │ — ┆ — ┆ — ┆ — ┆ lity │ │ i64 ┆ datetime[ns] ┆ bool ┆ bool ┆ — │ │ ┆ ┆ ┆ ┆ f64 │ ╞════════════╪═════════════════════╪═══════════════╪═════════════════════════╪═══════════════════════════╡ │ 1 ┆ 2020-01-01 00:00:00 ┆ … ┆ … ┆ … │ │ 2 ┆ 2020-01-02 00:00:00 ┆ … ┆ … ┆ … │ └────────────┴─────────────────────┴───────────────┴─────────────────────────┴───────────────────────────┘
Source code in meds_torch/predict.py
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 | |
process_predictions(predictions, model_keys)
Process predictions and create a Polars DataFrame handling tensors of different dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions |
list[dict[str, Any]]
|
List of prediction batches |
required |
model_keys |
dict[str, str]
|
Dictionary mapping model keys to schema names |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars DataFrame with processed data |
Examples:
Mixed dimension example with MODEL// prefixed keys
batch1 = { … ‘1d’: torch.tensor([1., 2.]), … ‘2d’: torch.tensor([[3., 4.], [5., 6.]]), … ‘3d’: torch.tensor([[[7., 8.], [9., 10.]], [[11., 12.], [13., 14.]]]), … ‘MODEL//extra’: torch.tensor([[100., 200.], [300., 400.]]), … ‘MODEL//another’: torch.tensor([1000., 2000.]), … ‘not_model’: torch.tensor([9999., 8888.]) # Should be ignored … } batch2 = { … ‘1d’: torch.tensor([15., 16.]), … ‘2d’: torch.tensor([[17., 18.], [19., 20.]]), … ‘3d’: torch.tensor([[[21., 22.], [23., 24.]], [[25., 26.], [27., 28.]]]), … ‘MODEL//extra’: torch.tensor([[500., 600.], [700., 800.]]), … ‘MODEL//another’: torch.tensor([3000., 4000.]), … ‘not_model’: torch.tensor([7777., 6666.]) # Should be ignored … } predictions = [batch1, batch2] keys = {‘1d’: ‘scalar’, ‘2d’: ‘vector’, ‘3d’: ‘matrix’} df = process_predictions(predictions, keys) df.shape[0] # Number of rows 4 sorted_df = df.sort(“scalar”) sorted_df.columns [‘scalar’, ‘vector’, ‘matrix’, ‘MODEL//extra’, ‘MODEL//another’] len(sorted_df.columns) # Should include original columns plus MODEL_ columns 5 sorted_df shape: (4, 5) ┌────────┬──────────────┬──────────────────────────────┬────────────────┬────────────────┐ │ scalar ┆ vector ┆ matrix ┆ MODEL//extra ┆ MODEL//another │ │ — ┆ — ┆ — ┆ — ┆ — │ │ f64 ┆ list[f64] ┆ list[list[f64]] ┆ list[f64] ┆ f64 │ ╞════════╪══════════════╪══════════════════════════════╪════════════════╪════════════════╡ │ 1.0 ┆ [3.0, 4.0] ┆ [[7.0, 8.0], [9.0, 10.0]] ┆ [100.0, 200.0] ┆ 1000.0 │ │ 2.0 ┆ [5.0, 6.0] ┆ [[11.0, 12.0], [13.0, 14.0]] ┆ [300.0, 400.0] ┆ 2000.0 │ │ 15.0 ┆ [17.0, 18.0] ┆ [[21.0, 22.0], [23.0, 24.0]] ┆ [500.0, 600.0] ┆ 3000.0 │ │ 16.0 ┆ [19.0, 20.0] ┆ [[25.0, 26.0], [27.0, 28.0]] ┆ [700.0, 800.0] ┆ 4000.0 │ └────────┴──────────────┴──────────────────────────────┴────────────────┴────────────────┘
Test error handling
del predictions[1]['1d'] import pytest with pytest.raises(RuntimeError): … pytest.raises(process_predictions(predictions, keys))
Source code in meds_torch/predict.py
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 | |
process_tensor_batches(predictions, key)
Process tensor batches of different dimensions into a list suitable for Polars DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions |
list[dict[str, Any]]
|
List of dictionaries containing tensor batches |
required |
key |
str
|
Key to access the tensor in each batch |
required |
Returns:
| Type | Description |
|---|---|
list[Tensor | ndarray]
|
List where each element represents one row in the final DataFrame |
Examples:
1D tensor example
batch1 = {‘values’: torch.tensor([1., 2.])} batch2 = {‘values’: torch.tensor([3., 4.])} predictions = [batch1, batch2] result = process_tensor_batches(predictions, ‘values’) len(result) 4 result[0] 1.0
2D tensor example
batch1 = {‘matrix’: torch.tensor([[1., 2.], [3., 4.]])} batch2 = {‘matrix’: torch.tensor([[5., 6.], [7., 8.]])} predictions = [batch1, batch2] result = process_tensor_batches(predictions, ‘matrix’) len(result) 4 result[0][1.0, 2.0]
3D tensor example
batch1 = {‘tokens’: torch.tensor([[[1.], [3.]]])} batch2 = {‘tokens’: torch.tensor([[[9., 10.], [11., 12.]], [[13., 14.], [15., 16.]]])} predictions = [batch1, batch2] result = process_tensor_batches(predictions, ‘tokens’) len(result) 3 result[0][[1.0], [3.0]]