1

I'm using scipy.optimize.fmin to solve a simple optimization problem and trying to understand how to use it correctly

I created a function to optimize that returns one value (the one to optimize) and using 2 parameters that I want to find (alpha and beta).

def q_learning_model(params, *args):
    choices = list(args[0].choice.astype(int))
    rewards = list(args[0].reward.astype(int))

    num_of_trials = len(choices)

    prob_of_choice = [0]*num_of_trials
    accuracy = [0]*num_of_trials

    beta = params[0]
    alpha = params[1]

    for trial in range(num_of_trials):
        # do things

    return -(np.sum(np.log(prob_of_choice)))

x1=()
minimum = optimize.fmin(q_learning_model,x0=(1,0.1),args=(data[['choice','reward']], x1))

I know that I need to pass the functions itself (as a callable) , an initial guess and the rest of the arguments that the function (that is being optimized) needs - the data in my case.

I would expect it to run with args=data[['choice','reward']], but it only runs when I add another variable after (meaning I get an error if there is only one arg) - it is also running when I pass an empty tuple after the data.

From what I saw, fmin is taking x0 as the params argument to q_learning_model, so *args suppose to take any number of values (1 in my case - the data).

Am I missing something ? How should I call fmin correctly ?

M.F
  • 345
  • 3
  • 15
  • 1
    Try `args=(data[['choice','reward']],)` (i.e. wrap the desired argument in a tuple of length 1). – Warren Weckesser Apr 09 '19 at 15:13
  • Take a look at the question and my answer at https://stackoverflow.com/questions/31388319/passing-args-in-scipy-optimize-minimize-objective-function-getting-error-on-nu; is that effectively the same question as yours? – Warren Weckesser Apr 09 '19 at 15:15
  • @WarrenWeckesser it is running, but as I wrote it can run with anything as long as theres more than one argument there (e.g can be empty tuple , a real value or whatever) . My question is why there's need in another argument there, and if I'm using the whole thing correctly . – M.F Apr 09 '19 at 15:49

0 Answers0