I noticed I tend to use many if-conditions in my code, and I know there is a way to simplify this with one-liners.
The function is iterating through configuration dictionaries so that I can log parameters in MLflow not as a long non-readable string:
but as key-value pairs:
!pip install mlflow
!python -m pip install -e detectron2
import mlflow
import detectron2
from detectron2.config import get_cfg, CfgNode
cfg = get_cfg()
for k, v in cfg.items():
# (1) check if params are being logged as a long hard-to-read string
if type(v) == detectron2.config.config.CfgNode:
# (1) if yes, iterate through it to log separately
for kk, vv in v.items():
# (2) check again if params are being logged as a long hard-to-read string
if type(vv) == detectron2.config.config.CfgNode:
# (2) if yes, iterate through it to log separately
for kkk, vvv in vv.items():
# (3) check again if params are being logged as a long hard-to-read string
if type(vvv) == detectron2.config.config.CfgNode:
# (3) if yes, iterate through it to log separately
for kkkk, vvvv in vvv.items():
# (3) generate param_name
param_name = k + '.' + kk + '.' + kkk + '.' + kkkk
print(param_name, ':', vvvv)
# (3) log if exists
if vvvv:
mlflow.log_param(param_name, vvvv)
# (3) if not a dict
else:
# (3) generate param_name
param_name = k + '.' + kk + '.' + kkk
print(param_name, ':', vvv)
# (3) log if variable exists
if vvv:
mlflow.log_param(param_name, vvv)
# (2) if not a dict
else:
# (2) generate param_name
param_name = k + '.' + kk
print(param_name, ':', vv)
# (2) log if exists
if vv:
mlflow.log_param(param_name, vv)
# (1) if not a dict
else:
print(k, ':', v)
# (1) log if exists
if v:
mlflow.log_param(k, v)
I would gladly provide you with more details if necessary. Thanks in advance for all the tips and suggestions!