dragon-ml-toolbox 13.7.0__py3-none-any.whl → 13.8.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of dragon-ml-toolbox might be problematic. Click here for more details.
- {dragon_ml_toolbox-13.7.0.dist-info → dragon_ml_toolbox-13.8.0.dist-info}/METADATA +1 -1
- {dragon_ml_toolbox-13.7.0.dist-info → dragon_ml_toolbox-13.8.0.dist-info}/RECORD +9 -9
- ml_tools/ML_utilities.py +253 -4
- ml_tools/custom_logger.py +26 -8
- ml_tools/keys.py +8 -0
- {dragon_ml_toolbox-13.7.0.dist-info → dragon_ml_toolbox-13.8.0.dist-info}/WHEEL +0 -0
- {dragon_ml_toolbox-13.7.0.dist-info → dragon_ml_toolbox-13.8.0.dist-info}/licenses/LICENSE +0 -0
- {dragon_ml_toolbox-13.7.0.dist-info → dragon_ml_toolbox-13.8.0.dist-info}/licenses/LICENSE-THIRD-PARTY.md +0 -0
- {dragon_ml_toolbox-13.7.0.dist-info → dragon_ml_toolbox-13.8.0.dist-info}/top_level.txt +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
dragon_ml_toolbox-13.
|
|
2
|
-
dragon_ml_toolbox-13.
|
|
1
|
+
dragon_ml_toolbox-13.8.0.dist-info/licenses/LICENSE,sha256=L35WDmmLZNTlJvxF6Vy7Uy4SYNi6rCfWUqlTHpoRMoU,1081
|
|
2
|
+
dragon_ml_toolbox-13.8.0.dist-info/licenses/LICENSE-THIRD-PARTY.md,sha256=iy2r_R7wjzsCbz_Q_jMsp_jfZ6oP8XW9QhwzRBH0mGY,1904
|
|
3
3
|
ml_tools/ETL_cleaning.py,sha256=2VBRllV8F-ZiPylPp8Az2gwn5ztgazN0BH5OKnRUhV0,20402
|
|
4
4
|
ml_tools/ETL_engineering.py,sha256=KfYqgsxupAx6e_TxwO1LZXeu5mFkIhVXJrNjP3CzIZc,54927
|
|
5
5
|
ml_tools/GUI_tools.py,sha256=Va6ig-dHULPVRwQYYtH3fvY5XPIoqRcJpRW8oXC55Hw,45413
|
|
@@ -13,7 +13,7 @@ ml_tools/ML_models.py,sha256=UVWJHPLVIvFno_csCHH1FwBfTwQ5nX0V8F1TbOByZ4I,31388
|
|
|
13
13
|
ml_tools/ML_optimization.py,sha256=P0zkhKAwTpkorIBtR0AOIDcyexo5ngmvFUzo3DfNO-E,22692
|
|
14
14
|
ml_tools/ML_scaler.py,sha256=tw6onj9o8_kk3FQYb930HUzvv1zsFZe2YZJdF3LtHkU,7538
|
|
15
15
|
ml_tools/ML_trainer.py,sha256=ZxeOagXW5adFhYIH-oMTlcrLU6VHe4R1EROI7yypNwQ,29665
|
|
16
|
-
ml_tools/ML_utilities.py,sha256=
|
|
16
|
+
ml_tools/ML_utilities.py,sha256=QC44y5mAzA6iUdb3py0bjI-nPjxUatZTdm8sMrb3He0,19364
|
|
17
17
|
ml_tools/PSO_optimization.py,sha256=T-HWHMRJUnPvPwixdU5jif3_rnnI36TzcL8u3oSCwuA,22960
|
|
18
18
|
ml_tools/RNN_forecast.py,sha256=Qa2KoZfdAvSjZ4yE78N4BFXtr3tTr0Gx7tQJZPotsh0,1967
|
|
19
19
|
ml_tools/SQL.py,sha256=vXLPGfVVg8bfkbBE3HVfyEclVbdJy0TBhuQONtMwSCQ,11234
|
|
@@ -23,19 +23,19 @@ ml_tools/_logger.py,sha256=dlp5cGbzooK9YSNSZYB4yjZrOaQUGW8PTrM411AOvL8,4717
|
|
|
23
23
|
ml_tools/_schema.py,sha256=yu6aWmn_2Z4_AxAtJGDDCIa96y6JcUp-vgnCS013Qmw,3908
|
|
24
24
|
ml_tools/_script_info.py,sha256=21r83LV3RubsNZ_RTEUON6RbDf7Mh4_udweNcvdF_Fk,212
|
|
25
25
|
ml_tools/constants.py,sha256=3br5Rk9cL2IUo638eJuMOGdbGQaWssaUecYEvSeRBLM,3322
|
|
26
|
-
ml_tools/custom_logger.py,sha256=
|
|
26
|
+
ml_tools/custom_logger.py,sha256=i0cAr1qPnwXDyqQ1itk2o72-2jniRXJNEuST2eW4zF4,11016
|
|
27
27
|
ml_tools/data_exploration.py,sha256=-BbWO7BBFapPi_7ZuWo65VqguJXaBfgFSptrXyoWrDk,51902
|
|
28
28
|
ml_tools/ensemble_evaluation.py,sha256=FGHSe8LBI8_w8LjNeJWOcYQ1UK_mc6fVah8gmSvNVGg,26853
|
|
29
29
|
ml_tools/ensemble_inference.py,sha256=0yLmLNj45RVVoSCLH1ZYJG9IoAhTkWUqEZmLOQTFGTY,9348
|
|
30
30
|
ml_tools/ensemble_learning.py,sha256=vsIED7nlheYI4w2SBzP6SC1AnNeMfn-2A1Gqw5EfxsM,21964
|
|
31
31
|
ml_tools/handle_excel.py,sha256=pfdAPb9ywegFkM9T54bRssDOsX-K7rSeV0RaMz7lEAo,14006
|
|
32
|
-
ml_tools/keys.py,sha256=
|
|
32
|
+
ml_tools/keys.py,sha256=CcqE9R9R32osR0vLz0i-3cyv1UlVsDWAHqvlVf8xm_0,2492
|
|
33
33
|
ml_tools/math_utilities.py,sha256=xeKq1quR_3DYLgowcp4Uam_4s3JltUyOnqMOGuAiYWU,8802
|
|
34
34
|
ml_tools/optimization_tools.py,sha256=TYFQ2nSnp7xxs-VyoZISWgnGJghFbsWasHjruegyJRs,12763
|
|
35
35
|
ml_tools/path_manager.py,sha256=CyDU16pOKmC82jPubqJPT6EBt-u-3rGVbxyPIZCvDDY,18432
|
|
36
36
|
ml_tools/serde.py,sha256=c8uDYjYry_VrLvoG4ixqDj5pij88lVn6Tu4NHcPkwDU,6943
|
|
37
37
|
ml_tools/utilities.py,sha256=aWqvYzmxlD74PD5Yqu1VuTekDJeYLQrmPIU_VeVyRp0,22526
|
|
38
|
-
dragon_ml_toolbox-13.
|
|
39
|
-
dragon_ml_toolbox-13.
|
|
40
|
-
dragon_ml_toolbox-13.
|
|
41
|
-
dragon_ml_toolbox-13.
|
|
38
|
+
dragon_ml_toolbox-13.8.0.dist-info/METADATA,sha256=mvK0WY75d25CARpUbiDoaK3PHtVgRIEcCauCo7RT6wU,6166
|
|
39
|
+
dragon_ml_toolbox-13.8.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
40
|
+
dragon_ml_toolbox-13.8.0.dist-info/top_level.txt,sha256=wm-oxax3ciyez6VoO4zsFd-gSok2VipYXnbg3TH9PtU,9
|
|
41
|
+
dragon_ml_toolbox-13.8.0.dist-info/RECORD,,
|
ml_tools/ML_utilities.py
CHANGED
|
@@ -1,18 +1,24 @@
|
|
|
1
1
|
import pandas as pd
|
|
2
2
|
from pathlib import Path
|
|
3
|
-
from typing import Union, Any, Optional
|
|
3
|
+
from typing import Union, Any, Optional, Dict, List, Iterable
|
|
4
|
+
import torch
|
|
5
|
+
from torch import nn
|
|
6
|
+
|
|
4
7
|
|
|
5
8
|
from .path_manager import make_fullpath, list_subdirectories, list_files_by_extension
|
|
6
9
|
from ._script_info import _script_info
|
|
7
10
|
from ._logger import _LOGGER
|
|
8
|
-
from .keys import DatasetKeys, PytorchModelArchitectureKeys, PytorchArtifactPathKeys, SHAPKeys
|
|
11
|
+
from .keys import DatasetKeys, PytorchModelArchitectureKeys, PytorchArtifactPathKeys, SHAPKeys, UtilityKeys, PyTorchCheckpointKeys
|
|
9
12
|
from .utilities import load_dataframe
|
|
10
|
-
from .custom_logger import save_list_strings
|
|
13
|
+
from .custom_logger import save_list_strings, custom_logger
|
|
11
14
|
|
|
12
15
|
|
|
13
16
|
__all__ = [
|
|
14
17
|
"find_model_artifacts",
|
|
15
|
-
"select_features_by_shap"
|
|
18
|
+
"select_features_by_shap",
|
|
19
|
+
"get_model_parameters",
|
|
20
|
+
"inspect_pth_file",
|
|
21
|
+
"set_parameter_requires_grad"
|
|
16
22
|
]
|
|
17
23
|
|
|
18
24
|
|
|
@@ -226,5 +232,248 @@ def select_features_by_shap(
|
|
|
226
232
|
return final_features
|
|
227
233
|
|
|
228
234
|
|
|
235
|
+
def get_model_parameters(model: nn.Module, save_dir: Optional[Union[str,Path]]=None) -> Dict[str, int]:
|
|
236
|
+
"""
|
|
237
|
+
Calculates the total and trainable parameters of a PyTorch model.
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
model (nn.Module): The PyTorch model to inspect.
|
|
241
|
+
save_dir: Optional directory to save the output as a JSON file.
|
|
242
|
+
|
|
243
|
+
Returns:
|
|
244
|
+
Dict[str, int]: A dictionary containing:
|
|
245
|
+
- "total_params": The total number of parameters.
|
|
246
|
+
- "trainable_params": The number of trainable parameters (where requires_grad=True).
|
|
247
|
+
"""
|
|
248
|
+
total_params = sum(p.numel() for p in model.parameters())
|
|
249
|
+
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
|
250
|
+
|
|
251
|
+
report = {
|
|
252
|
+
UtilityKeys.TOTAL_PARAMS: total_params,
|
|
253
|
+
UtilityKeys.TRAINABLE_PARAMS: trainable_params
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if save_dir is not None:
|
|
257
|
+
output_dir = make_fullpath(save_dir, make=True, enforce="directory")
|
|
258
|
+
custom_logger(data=report,
|
|
259
|
+
save_directory=output_dir,
|
|
260
|
+
log_name=UtilityKeys.MODEL_PARAMS_FILE,
|
|
261
|
+
dict_as="json")
|
|
262
|
+
|
|
263
|
+
return report
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def inspect_pth_file(
|
|
267
|
+
pth_path: Union[str, Path],
|
|
268
|
+
save_dir: Union[str, Path],
|
|
269
|
+
) -> None:
|
|
270
|
+
"""
|
|
271
|
+
Inspects a .pth file (e.g., checkpoint) and saves a human-readable
|
|
272
|
+
JSON summary of its contents.
|
|
273
|
+
|
|
274
|
+
Args:
|
|
275
|
+
pth_path (str | Path): The path to the .pth file to inspect.
|
|
276
|
+
save_dir (str | Path): The directory to save the JSON report.
|
|
277
|
+
|
|
278
|
+
Returns:
|
|
279
|
+
Dict (str, Any): A dictionary containing the inspection report.
|
|
280
|
+
|
|
281
|
+
Raises:
|
|
282
|
+
ValueError: If the .pth file is empty or in an unrecognized format.
|
|
283
|
+
"""
|
|
284
|
+
# --- 1. Validate paths ---
|
|
285
|
+
pth_file = make_fullpath(pth_path, enforce="file")
|
|
286
|
+
output_dir = make_fullpath(save_dir, make=True, enforce="directory")
|
|
287
|
+
pth_name = pth_file.stem
|
|
288
|
+
|
|
289
|
+
# --- 2. Load data ---
|
|
290
|
+
try:
|
|
291
|
+
# Load onto CPU to avoid GPU memory issues
|
|
292
|
+
loaded_data = torch.load(pth_file, map_location=torch.device('cpu'))
|
|
293
|
+
except Exception as e:
|
|
294
|
+
_LOGGER.error(f"Failed to load .pth file '{pth_file}': {e}")
|
|
295
|
+
raise
|
|
296
|
+
|
|
297
|
+
# --- 3. Initialize Report ---
|
|
298
|
+
report = {
|
|
299
|
+
"top_level_type": str(type(loaded_data)),
|
|
300
|
+
"top_level_summary": {},
|
|
301
|
+
"model_state_analysis": None,
|
|
302
|
+
"notes": []
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
# --- 4. Parse loaded data ---
|
|
306
|
+
if isinstance(loaded_data, dict):
|
|
307
|
+
# --- Case 1: Loaded data is a dictionary (most common case) ---
|
|
308
|
+
# "main loop" that iterates over *everything* first.
|
|
309
|
+
for key, value in loaded_data.items():
|
|
310
|
+
key_summary = {}
|
|
311
|
+
val_type = str(type(value))
|
|
312
|
+
key_summary["type"] = val_type
|
|
313
|
+
|
|
314
|
+
if isinstance(value, torch.Tensor):
|
|
315
|
+
key_summary["shape"] = list(value.shape)
|
|
316
|
+
key_summary["dtype"] = str(value.dtype)
|
|
317
|
+
elif isinstance(value, dict):
|
|
318
|
+
key_summary["key_count"] = len(value)
|
|
319
|
+
key_summary["key_preview"] = list(value.keys())[:5]
|
|
320
|
+
elif isinstance(value, (int, float, str, bool)):
|
|
321
|
+
key_summary["value_preview"] = str(value)
|
|
322
|
+
elif isinstance(value, (list, tuple)):
|
|
323
|
+
key_summary["value_preview"] = str(value)[:100]
|
|
324
|
+
|
|
325
|
+
report["top_level_summary"][key] = key_summary
|
|
326
|
+
|
|
327
|
+
# Now, try to find the model state_dict within the dict
|
|
328
|
+
if PyTorchCheckpointKeys.MODEL_STATE in loaded_data and isinstance(loaded_data[PyTorchCheckpointKeys.MODEL_STATE], dict):
|
|
329
|
+
report["notes"].append(f"Found standard checkpoint key: '{PyTorchCheckpointKeys.MODEL_STATE}'. Analyzing as model state_dict.")
|
|
330
|
+
state_dict = loaded_data[PyTorchCheckpointKeys.MODEL_STATE]
|
|
331
|
+
report["model_state_analysis"] = _generate_weight_report(state_dict)
|
|
332
|
+
|
|
333
|
+
elif all(isinstance(v, torch.Tensor) for v in loaded_data.values()):
|
|
334
|
+
report["notes"].append("File dictionary contains only tensors. Analyzing entire dictionary as model state_dict.")
|
|
335
|
+
state_dict = loaded_data
|
|
336
|
+
report["model_state_analysis"] = _generate_weight_report(state_dict)
|
|
337
|
+
|
|
338
|
+
else:
|
|
339
|
+
report["notes"].append("Could not identify a single model state_dict. See top_level_summary for all contents. No detailed weight analysis will be performed.")
|
|
340
|
+
|
|
341
|
+
elif isinstance(loaded_data, nn.Module):
|
|
342
|
+
# --- Case 2: Loaded data is a full pickled model ---
|
|
343
|
+
# _LOGGER.warning("Loading a full, pickled nn.Module is not recommended. Inspecting its state_dict().")
|
|
344
|
+
report["notes"].append("File is a full, pickled nn.Module. This is not recommended. Extracting state_dict() for analysis.")
|
|
345
|
+
state_dict = loaded_data.state_dict()
|
|
346
|
+
report["model_state_analysis"] = _generate_weight_report(state_dict)
|
|
347
|
+
|
|
348
|
+
else:
|
|
349
|
+
# --- Case 3: Unrecognized format (e.g., single tensor, list) ---
|
|
350
|
+
_LOGGER.error(f"Could not parse .pth file. Loaded data is of type {type(loaded_data)}, not a dict or nn.Module.")
|
|
351
|
+
raise ValueError()
|
|
352
|
+
|
|
353
|
+
# --- 5. Save Report ---
|
|
354
|
+
custom_logger(data=report,
|
|
355
|
+
save_directory=output_dir,
|
|
356
|
+
log_name=UtilityKeys.PTH_FILE + pth_name,
|
|
357
|
+
dict_as="json")
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _generate_weight_report(state_dict: dict) -> dict:
|
|
361
|
+
"""
|
|
362
|
+
Internal helper to analyze a state_dict and return a structured report.
|
|
363
|
+
|
|
364
|
+
Args:
|
|
365
|
+
state_dict (dict): The model state_dict to analyze.
|
|
366
|
+
|
|
367
|
+
Returns:
|
|
368
|
+
dict: A report containing total parameters and a per-parameter breakdown.
|
|
369
|
+
"""
|
|
370
|
+
weight_report = {}
|
|
371
|
+
total_params = 0
|
|
372
|
+
if not isinstance(state_dict, dict):
|
|
373
|
+
_LOGGER.warning(f"Attempted to generate weight report on non-dict type: {type(state_dict)}")
|
|
374
|
+
return {"error": "Input was not a dictionary."}
|
|
375
|
+
|
|
376
|
+
for key, tensor in state_dict.items():
|
|
377
|
+
if not isinstance(tensor, torch.Tensor):
|
|
378
|
+
_LOGGER.warning(f"Skipping key '{key}' in state_dict: value is not a tensor (type: {type(tensor)}).")
|
|
379
|
+
weight_report[key] = {
|
|
380
|
+
"type": str(type(tensor)),
|
|
381
|
+
"value_preview": str(tensor)[:50] # Show a preview
|
|
382
|
+
}
|
|
383
|
+
continue
|
|
384
|
+
weight_report[key] = {
|
|
385
|
+
"shape": list(tensor.shape),
|
|
386
|
+
"dtype": str(tensor.dtype),
|
|
387
|
+
"requires_grad": tensor.requires_grad,
|
|
388
|
+
"num_elements": tensor.numel()
|
|
389
|
+
}
|
|
390
|
+
total_params += tensor.numel()
|
|
391
|
+
|
|
392
|
+
return {
|
|
393
|
+
"total_parameters": total_params,
|
|
394
|
+
"parameter_key_count": len(weight_report),
|
|
395
|
+
"parameters": weight_report
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def set_parameter_requires_grad(
|
|
400
|
+
model: nn.Module,
|
|
401
|
+
unfreeze_last_n_params: int,
|
|
402
|
+
) -> int:
|
|
403
|
+
"""
|
|
404
|
+
Freezes or unfreezes parameters in a model based on unfreeze_last_n_params.
|
|
405
|
+
|
|
406
|
+
- N = 0: Freezes ALL parameters.
|
|
407
|
+
- N > 0 and N < total: Freezes ALL parameters, then unfreezes the last N.
|
|
408
|
+
- N >= total: Unfreezes ALL parameters.
|
|
409
|
+
|
|
410
|
+
Note: 'N' refers to individual parameter tensors (e.g., `layer.weight`
|
|
411
|
+
or `layer.bias`), not modules or layers. For example, to unfreeze
|
|
412
|
+
the final nn.Linear layer, you would use N=2 (for its weight and bias).
|
|
413
|
+
|
|
414
|
+
Args:
|
|
415
|
+
model (nn.Module): The model to modify.
|
|
416
|
+
unfreeze_last_n_params (int):
|
|
417
|
+
The number of parameter tensors to unfreeze, starting from
|
|
418
|
+
the end of the model.
|
|
419
|
+
|
|
420
|
+
Returns:
|
|
421
|
+
int: The total number of individual parameters (elements) that were set to `requires_grad=True`.
|
|
422
|
+
"""
|
|
423
|
+
if unfreeze_last_n_params < 0:
|
|
424
|
+
_LOGGER.error(f"unfreeze_last_n_params must be >= 0, but got {unfreeze_last_n_params}")
|
|
425
|
+
raise ValueError()
|
|
426
|
+
|
|
427
|
+
# --- Step 1: Get all parameter tensors ---
|
|
428
|
+
all_params = list(model.parameters())
|
|
429
|
+
total_param_tensors = len(all_params)
|
|
430
|
+
|
|
431
|
+
# --- Case 1: N = 0 (Freeze ALL parameters) ---
|
|
432
|
+
# early exit for the "freeze all" case.
|
|
433
|
+
if unfreeze_last_n_params == 0:
|
|
434
|
+
params_frozen = _set_params_grad(all_params, requires_grad=False)
|
|
435
|
+
_LOGGER.warning(f"Froze all {total_param_tensors} parameter tensors ({params_frozen} total elements).")
|
|
436
|
+
return 0 # 0 parameters unfrozen
|
|
437
|
+
|
|
438
|
+
# --- Case 2: N >= total (Unfreeze ALL parameters) ---
|
|
439
|
+
if unfreeze_last_n_params >= total_param_tensors:
|
|
440
|
+
if unfreeze_last_n_params > total_param_tensors:
|
|
441
|
+
_LOGGER.warning(f"Requested to unfreeze {unfreeze_last_n_params} params, but model only has {total_param_tensors}. Unfreezing all.")
|
|
442
|
+
|
|
443
|
+
params_unfrozen = _set_params_grad(all_params, requires_grad=True)
|
|
444
|
+
_LOGGER.info(f"Unfroze all {total_param_tensors} parameter tensors ({params_unfrozen} total elements) for training.")
|
|
445
|
+
return params_unfrozen
|
|
446
|
+
|
|
447
|
+
# --- Case 3: 0 < N < total (Standard: Freeze all, unfreeze last N) ---
|
|
448
|
+
# Freeze ALL
|
|
449
|
+
params_frozen = _set_params_grad(all_params, requires_grad=False)
|
|
450
|
+
_LOGGER.info(f"Froze {params_frozen} parameters.")
|
|
451
|
+
|
|
452
|
+
# Unfreeze the last N
|
|
453
|
+
params_to_unfreeze = all_params[-unfreeze_last_n_params:]
|
|
454
|
+
|
|
455
|
+
# these are all False, so the helper will set them to True
|
|
456
|
+
params_unfrozen = _set_params_grad(params_to_unfreeze, requires_grad=True)
|
|
457
|
+
|
|
458
|
+
_LOGGER.info(f"Unfroze the last {unfreeze_last_n_params} parameter tensors ({params_unfrozen} total elements) for training.")
|
|
459
|
+
|
|
460
|
+
return params_unfrozen
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _set_params_grad(
|
|
464
|
+
params: Iterable[nn.Parameter],
|
|
465
|
+
requires_grad: bool
|
|
466
|
+
) -> int:
|
|
467
|
+
"""
|
|
468
|
+
A helper function to set the `requires_grad` attribute for an iterable
|
|
469
|
+
of parameters and return the total number of elements changed.
|
|
470
|
+
"""
|
|
471
|
+
params_changed = 0
|
|
472
|
+
for param in params:
|
|
473
|
+
if param.requires_grad != requires_grad:
|
|
474
|
+
param.requires_grad = requires_grad
|
|
475
|
+
params_changed += param.numel()
|
|
476
|
+
return params_changed
|
|
477
|
+
|
|
229
478
|
def info():
|
|
230
479
|
_script_info(__all__)
|
ml_tools/custom_logger.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
from pathlib import Path
|
|
2
2
|
from datetime import datetime
|
|
3
|
-
from typing import Union, List, Dict, Any
|
|
3
|
+
from typing import Union, List, Dict, Any, Literal
|
|
4
4
|
import traceback
|
|
5
5
|
import json
|
|
6
6
|
import csv
|
|
@@ -29,6 +29,7 @@ def custom_logger(
|
|
|
29
29
|
],
|
|
30
30
|
save_directory: Union[str, Path],
|
|
31
31
|
log_name: str,
|
|
32
|
+
dict_as: Literal['auto', 'json', 'csv'] = 'auto',
|
|
32
33
|
) -> None:
|
|
33
34
|
"""
|
|
34
35
|
Logs various data types to corresponding output formats:
|
|
@@ -36,10 +37,10 @@ def custom_logger(
|
|
|
36
37
|
- list[Any] → .txt
|
|
37
38
|
Each element is written on a new line.
|
|
38
39
|
|
|
39
|
-
- dict[str, list[Any]] → .csv
|
|
40
|
+
- dict[str, list[Any]] → .csv (if dict_as='auto' or 'csv')
|
|
40
41
|
Dictionary is treated as tabular data; keys become columns, values become rows.
|
|
41
42
|
|
|
42
|
-
- dict[str, scalar] → .json
|
|
43
|
+
- dict[str, scalar] → .json (if dict_as='auto' or 'json')
|
|
43
44
|
Dictionary is treated as structured data and serialized as JSON.
|
|
44
45
|
|
|
45
46
|
- str → .log
|
|
@@ -52,26 +53,43 @@ def custom_logger(
|
|
|
52
53
|
data: The data to be logged. Must be one of the supported types.
|
|
53
54
|
save_directory: Directory where the log will be saved. Created if it does not exist.
|
|
54
55
|
log_name: Base name for the log file. Timestamp will be appended automatically.
|
|
56
|
+
dict_as ('auto'|'json'|'csv'):
|
|
57
|
+
- 'auto': Guesses format (JSON or CSV) based on dictionary content.
|
|
58
|
+
- 'json': Forces .json format for any dictionary.
|
|
59
|
+
- 'csv': Forces .csv format. Will fail if dict values are not all lists.
|
|
55
60
|
|
|
56
61
|
Raises:
|
|
57
62
|
ValueError: If the data type is unsupported.
|
|
58
63
|
"""
|
|
59
64
|
try:
|
|
65
|
+
if not isinstance(data, BaseException) and not data:
|
|
66
|
+
_LOGGER.warning("Empty data received. No log file will be saved.")
|
|
67
|
+
return
|
|
68
|
+
|
|
60
69
|
save_path = make_fullpath(save_directory, make=True)
|
|
61
70
|
|
|
62
71
|
timestamp = datetime.now().strftime(r"%Y%m%d_%H%M%S")
|
|
63
72
|
log_name = sanitize_filename(log_name)
|
|
64
73
|
|
|
65
74
|
base_path = save_path / f"{log_name}_{timestamp}"
|
|
66
|
-
|
|
75
|
+
|
|
76
|
+
# Router
|
|
67
77
|
if isinstance(data, list):
|
|
68
78
|
_log_list_to_txt(data, base_path.with_suffix(".txt"))
|
|
69
79
|
|
|
70
80
|
elif isinstance(data, dict):
|
|
71
|
-
if
|
|
72
|
-
_log_dict_to_csv(data, base_path.with_suffix(".csv"))
|
|
73
|
-
else:
|
|
81
|
+
if dict_as == 'json':
|
|
74
82
|
_log_dict_to_json(data, base_path.with_suffix(".json"))
|
|
83
|
+
|
|
84
|
+
elif dict_as == 'csv':
|
|
85
|
+
# This will raise a ValueError if data is not all lists
|
|
86
|
+
_log_dict_to_csv(data, base_path.with_suffix(".csv"))
|
|
87
|
+
|
|
88
|
+
else: # 'auto' mode
|
|
89
|
+
if all(isinstance(v, list) for v in data.values()):
|
|
90
|
+
_log_dict_to_csv(data, base_path.with_suffix(".csv"))
|
|
91
|
+
else:
|
|
92
|
+
_log_dict_to_json(data, base_path.with_suffix(".json"))
|
|
75
93
|
|
|
76
94
|
elif isinstance(data, str):
|
|
77
95
|
_log_string_to_log(data, base_path.with_suffix(".log"))
|
|
@@ -83,7 +101,7 @@ def custom_logger(
|
|
|
83
101
|
_LOGGER.error("Unsupported data type. Must be list, dict, str, or BaseException.")
|
|
84
102
|
raise ValueError()
|
|
85
103
|
|
|
86
|
-
_LOGGER.info(f"Log saved
|
|
104
|
+
_LOGGER.info(f"Log saved as: '{base_path.name}'")
|
|
87
105
|
|
|
88
106
|
except Exception:
|
|
89
107
|
_LOGGER.exception(f"Log not saved.")
|
ml_tools/keys.py
CHANGED
|
@@ -80,6 +80,14 @@ class PyTorchCheckpointKeys:
|
|
|
80
80
|
BEST_SCORE = "best_score"
|
|
81
81
|
|
|
82
82
|
|
|
83
|
+
class UtilityKeys:
|
|
84
|
+
"""Keys used for utility modules"""
|
|
85
|
+
MODEL_PARAMS_FILE = "model_parameters"
|
|
86
|
+
TOTAL_PARAMS = "Total Parameters"
|
|
87
|
+
TRAINABLE_PARAMS = "Trainable Parameters"
|
|
88
|
+
PTH_FILE = "pth report "
|
|
89
|
+
|
|
90
|
+
|
|
83
91
|
class _OneHotOtherPlaceholder:
|
|
84
92
|
"""Used internally by GUI_tools."""
|
|
85
93
|
OTHER_GUI = "OTHER"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|