Home > Enterprise >  python function change hyperparameter name
python function change hyperparameter name

Time:06-01

def wklearnerExp(hyparam="max_depth"):
    param = np.arange(1,200, 5)
    for p in param:
        wkClf = DecisionTreeClassifier(max_depth=p) # Change max_depth to a hyparam defined  at hyparam="max_depth"

For the funciton above, would it be possible to change the hyperparameter name "max_depth" to something else, such as "min_samples_leaf"? So that I can do:

wklearnerExp(hyparam="min_samples_leaf")

and swap the hyper parameter in the function while not rewrite the whole code again.

I've tried the following but not working

wkClf = DecisionTreeClassifier(eval(hyparam)=p)

Thanks!

CodePudding user response:

This will do it:

def wklearnerExp(hyparam="max_depth"):
    param = np.arange(1,200, 5)
    for p in param:
        wkClf = DecisionTreeClassifier(**{hyparam: p}) 

The ** operator converts a dictionary to keyword arguments. Whether it is a good idea or not is debatable.

  • Related