Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically calling and assigning a variable from a config python files

I have a list of parameters in a config file, if a specific model file is called in my script I want to dynamically assign the appropriate parameters to the variable name

config file looks like this:

tune_model_selection = ['logreg_module', 'random_forest_module']

logreg_module_tune_parameter_grid = {
"C": [0.01, 0.1, 1.0, 1.5, 2.0, 5.0, 10.0],
"class_weight": ['balanced', None],
"penalty": ['l2'],
"solver": ['newton-cg', 'lbfgs', 'liblinear']
}


random_forest_module_tune_parameter_grid = {
"n_estimators" : [100, 300, 500, 800, 1200],
"max_depth" : [5, 8, 15, 25, 30],
"min_samples_split" : [2, 5, 10, 15, 100],
"min_samples_leaf" : [1, 2, 5, 10] 
}

snippet of python script

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 class Tune:

def __init__(self,
             dataframe,
             text_column,
             target_column_name,
             date_column,
             config,
             model_file #logreg_module or random_forest_module
             ):
    if model_file in config.tune_model_selection:
        self.config = config
        self.text_column = text_column
        self.model_type = config.tune_model_type[model_file]
        self.model_module = importlib.import_module('modules.' + model_file) 
        
        #model file =  "logreg_module" or "random_forest_module"
        param_grid = model_file + '_tune_parameter_grid'
        self.parameter_grid = config.param_grid

For the variable self.parameter_grid, I want it to call config.random_forest_module_tune_parameter_grid dictionary or config.logreg_module_tune_parameter_grid

how it is scripted right now, it throws an error of no variable in config file named "param_grid"

I instead want it to read the name of param_grid from the previous variable and find the dictionary with associated parameters dynamically in the config file

>Solution :

This is what getattr is for. You can look up attributes using strings.

        self.parameter_grid = getattr(config, param_grid)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading