0

I am using the SLSQP algorithm for an minimization problem.

Here is my code:

import pandas as pd
import numpy as np
from scipy.optimize import minimize, Bounds

df = pd.DataFrame(np.random.rand(750,5),columns=['pred','var1','start'])

def obj(x,df=df):
  return -(x*df['pred']).sum()

def c1(x,df=df):
  return abs((x*df['var1']).sum())-0.05

def c2(x):
  return sum(x)

def c3(x):
  return 2-sum(abs(x))

sol = minimize(
    fun=er,
    x0=df['start'],
    method='SLSQP',
    bounds=Bounds(-1, 3),
    constraints=[{'type': 'ineq', 'fun': c1},{'type': 'eq', 'fun': c2},{'type': 'eq', 'fun': c3}],
    options={'maxiter': 1000})

I don't think that this can be rewritten as an LP because c3 has an absolute value function.

Open to any other ideas.

lara_toff
  • 413
  • 2
  • 14
  • do not use pandas objects in your functions, better use numpy. I guess that slows down your algorithm by a lot, e.g. use `df['pred'].values` in first function and `np.sum()` – dankal444 Nov 23 '22 at 20:16
  • python function `sum()` is gonna be slow too, use `np.sum` in c2 and c3 as well – dankal444 Nov 23 '22 at 20:16
  • @joni what do you mean introduce non-negative variables? they must be positive a negative to make c2 possible. – lara_toff Nov 23 '22 at 21:50
  • @joni also c3 is not an inequality its an equality. doesn't that make an LP impossible? – lara_toff Nov 23 '22 at 23:53
  • @joni sorry i don't follow, how do I just introduce a new optimization variable and set it to the absolute value of x? – lara_toff Nov 24 '22 at 11:22
  • @joni ok i got it working with some of hte constraints but the solution is nowhere as optimal as what SLSQP spits out... seems to get stuck on a local minimum thats very close to the bounds. Thanks for your help, I will have to figure out another way to speed up SLSQP – lara_toff Nov 24 '22 at 11:44
  • no it works, its just providing a very poor answer. that isn't unexpected as there would be many different local minima given 750 different variables. – lara_toff Nov 24 '22 at 12:30

0 Answers0