0

I have the following functions:

def train(data,**kwargs):
    train_model(data,**kwargs)

def test_train_parameters(data1,data2,parameter_to_test, parameter_value):
    train(data1,**kwargs)
    train(data2,**kwargs)

Train function has some optional parameters, such as gamma, lambda, num_rounds and so on. Train with data1 would be called without any modified parameter, but train with data2 would be called with a parameter modified and it's value. For example, let's say I want a gamma = 5, I would code:

test_train_parameters(parameter_to_test = 'gamma', parameter_value = 5)

And the function would be called as follow:

train(data1)
train(data2, gamma = 5)

Thus, this can not be done just calling the parameter as test_train_parameters(gamma = 5)because it would interfere with the first train.

I have been searching on google but I have been unable to find something that fits my case (I have found eval, getattr, passing list... but those are for other things). How could I make it?

2
  • 1
    What if you pass two dictionaries (one specifically for each train) - therefore parameters could be passed explicitly. Commented Aug 8, 2019 at 16:09
  • 4
    You can just do train(data2,**kwargs, **{parameter_to_test: parameter_value}). Or if parameter_to_test may appear in kwargs, do train(data1,**kwargs); kwargs[parameter_to_test] = parameter_value; train(data2,**kwargs). Commented Aug 8, 2019 at 16:10

2 Answers 2

4

In python, kwargs are just dictionaries, so you can create a dictionary in your function with your arguments:

def test_train_parameters(data1,data2,parameter_to_test, parameter_value):
    train(data1)
    kwargs = {parameter_to_test: parameter_value}
    train(data2,**kwargs)
Sign up to request clarification or add additional context in comments.

1 Comment

What if I already have other parameters passing as kwargs? Making kwargs[parameter_to_test] = parameter_value would be enough to add this one to the others?
1

An if with every possible parameter? Like

def test_train_parameters(data1,data2,parameter_to_test, parameter_value):
    train(data1)
    if parameter_to_test == 'alpha':
        train(data2, alpha=parameter_value)
    elif parameter_to_test == 'beta':
        train(data2, beta=parameter_value)
    elif parameter_to_test == 'gamma':
        train(data2, gamma=parameter_value)

I know it's not pleasing to the eye but it's a simple way to do it.

1 Comment

Well, there are like 50 parameters that can be modified, so it will be very tedious to make such a solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.