Search code examples
pythonargumentskeywordkeyword-argument

How to pass variable keyword-arguments when calling a function


I am trying to write a function which tests out different hyper-parameters with a list of values. I want to use this function to automatically run through the specified hyper-parameter and apply the values that are specified. What would be the correct way to do that? The correct way to call the logistic regression function would be:

lg = LogisticRegression(solver = "liblinear", max_iter = 10000, C=10)

def hyperparameter_tuning(parameter, test_values):
  for value in test_values:
     lg = LogisticRegression(solver = "liblinear", max_iter = 10000, parameter=value)

When calling the function like this:

hyperparameter_tuning("C",[0.1, 1, 10, 100])

I get the error message:

__init__() got an unexpected keyword argument 'parameter'

Solution

  • You should use ** for that:

    lg = LogisticRegression(solver = "liblinear", max_iter = 10000, **{parameter: value})