0

I have a function func(x) where the argument is a vector of length n. I would like to minimize it in respect to i-th component of x while keeping the other components fixed. So to express it as a function of a single component I would do something like

import numpy as np
from scipy.optimize import minimize_scalar

def func(x):
    #do some calculations
    return function_value

def func_i(x_i, x0, i):
    x = np.copy(x0)
    x[i] = x_i
    return func(x)

res = minimize_scalar(func_i, args=(x0, i))

Is there a more efficient way of doing this? This kind of calculations will be done repeatedly, cycling over variables, and I worry that x = np.copy(x0), x[i] = x_i slow down the calculation. (The problem emerges in the context of Gibbs sampling, so minimizing in respect to all the variables simultaneously is not what I want.)

6
  • 1
    You're varying one cell, so other cells don't change, right? Then you can only make a copy per cell, func_i will set a value in that cell to x_i as you do. Commented Jan 6 at 21:30
  • 1
    "I worry" - Don't just worry. Measure. Commented Jan 6 at 21:38
  • @nocomment a measurement makes sense only when compared with an alternative. Commented Jan 6 at 21:47
  • 1
    No. If you measure and find out that those actions only take 1% of the total time, then you know they don't (significantly) slow down the calculation. Commented Jan 6 at 21:53
  • 2
    It is worth looking at alternatives, but in Python it is possible that there isn't a faster way. Changing language to one that is fully compiled and optimised for native hardware is your other alternative if a significant performance improvement is essential. Commented Jan 8 at 13:02

1 Answer 1

1

One possible go faster option rather than a full copy of x0 is to require the function to put x0 back into the state it found it after making the evaluation. IOW func_i becomes:

 def func_i(x_i, x0, i)
     temp = x0[i]
     x0[i] = x_i
     result = func(x0)
     x0[i] = temp
     return result

This avoids the copy to x but requires 3 extra assignments instead. I don't know the length of your array x0 but I'd hazard a guess that it will be faster than a copy for lengths where n is large.

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

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.