0

how can i use "variable" constants in scipy.optimize functions? I am trying to create an iterative optimisation algorithm, which updates certain parameters in the objective function after each optimisation run.

to use a very simple example of what i want to do:

from scipy import optimize as opt

def f(x, R):
    return R * (x[0]**2 + x[1]**3)

R = 0.1 # initial R value
y = []
y.append([2,2]) # initial point

for i in range(0,10):
    y.append(opt.fmin(f, y[i])) # how can i include 'R' in this line??
    R = some_function_to_update_R(R)

any help would be appreciated

EDIT:
would it help to re-declare the objective function each time i optimise? so make the loop look like this instead?

for i in range(0,10):
    def f_temp(x_temp):
        return f(x_temp,R)
    y.append(opt.fmin(f_temp, y[i]))
    R = some_function_to_update_R(R)

or is there some better way?

1 Answer 1

2

fmin supports an optional args argument, representing a tuple of additional arguments to be passed to the function you're trying to optimize:

y.append(opt.fmin(f, y[i], args=(R,)))

This is explained in the documentation for fmin; you should get into the habit of checking the documentation when you want to figure out how to do something.

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

2 Comments

NOTE: Answers which suggest links to documentation should be STRICTLY left as comments. I urge the user to DELETE the last part of their answer or add it as a comment. It is against SO guidelines to suggest the user read the documentation as part of the answer.
@HamishGibson: Are you just trolling? Pointing users to documentation is totally fine. An answer that just links to the docs is link-only, which is discouraged, but this answer isn't link-only.

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.