1

I'm pretty new to python and I got stuck on this: I'd like to use scipy.optimize.minimize to maximize a function and I'm having some problem with the extra arguments of the function I defined.

I looked for a solution in tons of answered questions but I can't find anything that solves my problem. I saw in Structure of inputs to scipy minimize function how to pass extra arguments that one wants to be constant in the minimization of the function and my code seems fine to me from this point of view.

This is my code:

import numpy as np
from scipy.stats import pearsonr
import scipy.optimize as optimize

def min_pears_function(a,exp):
    (b,c,d,e)=a
    return (1-(pearsonr(b + exp[0] * c + exp[1] * d + exp[2],e)[0]))


a = (log_x,log_y,log_t,log_z) # where log_x, log_y, log_t and log_z are numpy arrays with same length

guess_PF=[0.6,2.0,0.2]

res = optimize.minimize(min_pears_function, guess_PF, args=(a,), options={'xtol': 1e-8, 'disp': True})

When running the code I get the following error:

ValueError: need more than 3 values to unpack

But I can't see what needed argument I'm missing. The function seems to work fine, so I guess the problem is in optimize.minimize call?

Community
  • 1
  • 1
aglaja
  • 21
  • 1
  • 6
  • Where does this `ValueError` occur? Give more of the traceback or a properly self-contained example – donkopotamus Oct 10 '16 at 22:29
  • Without the full stacktrace its difficult to say, but I would guess that if you put print(a) in your function you will find a = log_x,log_y,log_t and your error is generated on line (b,c,d,e)=a – Keith Bailey Oct 10 '16 at 22:30

1 Answers1

1

Your error occurs here:

def min_pears_function(a,exp):
    # XXX: This is your error line
    (b,c,d,e)=a
    return (1-(pearsonr(b + exp[0] * c + exp[1] * d + exp[2],e)[0]))

This is because:

  • the initial value you pass to optimize.minimize is guessPF which has just three values ([0.6,2.0,0.2]).
  • this initial value is passed to min_pears_function as the variable a.

Did you mean for it to be passed as exp? Is it exp you wish to solve for? In that case, redefine the signature as:

def min_pears_function(exp, a):
    ...
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
  • Mmm.. that's embarrassing.. so it's just a matter of ordered variables? Thanks donkopotamus! – aglaja Oct 10 '16 at 22:51