0

I am using scipy.optimize.minimize library to custom write my loss function. https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html

def customised_objective_func(x):
global lag1
global lag2
global lag3
global lag4

pred = []
err = []
df_col_others_copy=df_col_others.copy(deep=True)
df_col_others_copy*=np.array(x)
pred=intercept_val+df_col_others_copy.sum(axis=1)
pred=list(pred)
col_sales=list(df_col_sales)
err = np.array(pred) - np.array(col_sales)
#err = pred - col_sales
obj_func_cust=sum(err**2)/len(err) + (lambda_mult* pen_func(x))

# CONDITION CHECK
avg_lags_val=(lag1+lag2+lag3+lag4)/float(4.0)
perc_change=(np.abs(obj_func_cust-avg_lag_val)/float(avg_lags_val))*100

if perc_change>=2.0:
    break --###?? Sntax for breaking out here??

# retaining last 4 values
curr=obj_func_cust
lag4=lag3
lag3=lag2
lag2=lag1
lag1=curr

if curr=0:
    

return obj_func_cust

myoptions={'maxiter':1000}
results = minimize(customised_objective_func,params,method = "BFGS",options = myoptions) 

I am retaining the values of the loss function calculated for last 4 iterations and I want to check for some variance on them if that condition is met I want to stop the function call (quit further function execution for more iterations even if 1000 iterations are not complete.

How can I achieve this? Would appreciate help here with the keyword to be used/syntx?

Oshin Patwa
  • 105
  • 1
  • 8

2 Answers2

0

Since you need the last four objective function values and you can't terminate the solver inside your objective function, you can write a Wrapper that includes a callback and your objective function:

class Wrapper:
    def __init__(self, obj_fun, cond_fun, threshold):
        self.obj_fun = obj_fun
        self.cond_fun = cond_fun
        self.threshold = threshold
        self.last_vals = np.zeros(5)
        self.iters = 0

    def callback(self, xk):
        if self.iters <= 4:
            return False
        if self.cond_fun(self.last_vals) <= self.threshold:
            return True

    def objective(self, x):
        # evaluate the obj_fun, update the last four objective values
        # and return the current objective value
        np.roll(self.last_vals, 1)
        obj_val = self.obj_fun(x)
        self.last_vals[0] = obj_val
        self.iters += 1
        return obj_val

The callback method returns True and terminates the solver if your cond_fun evaluated at the last four values is below a given threshold. Here, xk is just the current point. The objective method is just a wrapper around your obj_fun and updates the last objective values.

Then, you can use it like this:

def your_cond_fun(last_obj_vals):
    curr = last_obj_vals[0]
    last4 = last_obj_vals[1:]
    avg_vals = np.sum(last4) / last4.size
    return 100*np.abs(curr - avg_vals) / avg_vals

wrapper = Wrapper(your_obj_fun, your_cond_fun, your_threshold)

minimize(wrapper.objective, params, callback = wrapper.callback, 
         method = "BFGS", options = myoptions) 
joni
  • 6,840
  • 2
  • 13
  • 20
  • So, I am trying to check for something within my customized function. I have edited the question to explain my concern in a better way. – Oshin Patwa Aug 19 '21 at 07:18
  • @OshinPatwa It isn't possible to terminate the solver within your objective function, so a callback is the only way to go. You can extend the above callback such that it stores the objective function values of the last four iterations. If there's interest, I can edit my answer. – joni Aug 19 '21 at 07:58
  • got it thanks. Yes sure could you please help me out about how exactly can I achieve this. – Oshin Patwa Aug 19 '21 at 09:26
0

Not all methods in optimize will terminate if callback returns True. Indeed, I remembered only one method will terminate as purposed, but I am not sure which one it is.

Checkout:https://github.com/scipy/scipy/pull/4384

Also, you can change the source code scipy.optimize._minimize to terminate when checking the callback.

Code snapshot like:

    if callback is not None:

        if unknown_options.get("early_stopping"):
            # NEW: update with early stopping
            res = callback(xk)
            if res:
                break
        else:
            callback(xk)
Kimmi
  • 591
  • 2
  • 7
  • 22