1

I am trying to use scipy.optimize.minimize (simplex method) for minimizing the following function

argmin (sum(i=0 to 9) (a*i - b_i)**2)

I would like to obtain the value of a. I have 10 values of b_i (i have it already calculated outside the function) that i want to insert in the function

def f(a, b):
    func = 0
    for i in range(10):
        func+= (a*i - b[i])**2
    return func
init = [1]
out= optimize.minimize(f, init, method='nelder-mead') 

it gives an error saying: f() missing 1 required positional argument: 'b'

How can i make it run.

3
  • What if you do init = [1 , 1]? You should pass two values to objective function. Or def f(a) (as you said b calculated already, then just remove it from arguments.) Commented Feb 15, 2022 at 16:12
  • but b is not one value, it has 10 values. I have corrected now. Commented Feb 15, 2022 at 16:15
  • Great! Put b[i] instead of b! I mean : func+= (a*i - b[i])**2 and also remove b from function arguments. Commented Feb 15, 2022 at 16:17

2 Answers 2

2

what about this:

def f(a):
    func = 0
    for i in range(10):
        func+= (a*i - b[i])**2
    return func
init = [1]
out= optimize.minimize(f, init, method='nelder-mead') 

as you said your target variable is a and you have values for b, then you need to construct Obj function with one argument I guess.

Sign up to request clarification or add additional context in comments.

2 Comments

where do i define b[i]? outside the function?
@Lalu Exactly before the function, you should define b! it should be something iterable like a list. for example: b = [1,2,3] (values maybe something else I don't know what they are.)
0

There is an optional parameter called args() in scipy.optimize.minimize using which you can pass arguments to the objective function as a tuple. You can do this as follows:

from scipy.optimize import minimize
b = [1,2,3,4,5,6,7,8,9,10] # for example

def f(a, b):
    func = 0
    for i in range(10):
        func+= (a*i - b[i])**2
    return func

init = [1]
out = minimize(f, init, args=(b), method='nelder-mead')
print(out)

Comments

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.