How can i adjust a parameter if there was no improvement after x iterations?
AnsweredI have the following (working) model, which i have to improve:
timeLimit=200
numVarAct=int(0.5*n)
numIterations=100
mdl.params.timeLimit=30
tm=time.time()
tm2=time.time()
while tm2-tm<timeLimit:
for i in V:
for m in M_i[i]:
x[i,m].lb=x[i,m].x
x[i,m].ub=x[i,m].x
actVar=np.random.choice(V,numVarAct,replace=False)
for i in actVar:
for m in M_i[i]:
x[i,m].lb=0
x[i,m].ub=1
mdl.optimize()
Can anyone help me how i can increase the parameter numVarAct by 1 if the objective value doesn't increased after say 5 iterations?
I assume that it's something in the form
if ... > ... :
numVarAct = numVarAct + 1
...but i have no idea how 1. define 5 iterations and 2. "measure" the improvement so that i can build an if - constraint.
-
Hi Celine,
Re 1: You can do that with help of a counter variable. You'd need to define it before your while loop, and then increase it by one every time you call mdl.optimize().
Re 2: This can be achieved by creating a list in which you'll store the solution values of consecutive runs. You would - again - need to initialize such a list before your while loop, and then - after each optimization call - query the optimal value parameter of your model and store it in the list you created (assuming that your models solve to optimality).
With these two at hand, you can create a condition that accounts for both the given number of iterations or the unchanging optimal solutions quality.
Your code could look something like this:
timeLimit=200
numVarAct=int(0.5*n)
numIterations=100
mdl.params.timeLimit=30
tm=time.time()
tm2=time.time()
solutions = []
counter = 0
while tm2-tm<timeLimit:
for i in V:
for m in M_i[i]:
x[i,m].lb=x[i,m].x
x[i,m].ub=x[i,m].x
actVar=np.random.choice(V,numVarAct,replace=False)
for i in actVar:
for m in M_i[i]:
x[i,m].lb=0
x[i,m].ub=1
mdl.optimize()
counter += 1
solutions.append(mdl.ObjVal)and the if-condition could look something like this:
if counter == 5 and solutions[0] == solutions[1] == solutions[2] == solutions[3] == solutions[4]:
numVarAct = numVarAct + 1You can obviously improve this code or adjust it to your needs.
Hope this helps.
Best regards
Jonasz0 -
thank you so much!
0
Please sign in to leave a comment.
Comments
2 comments