How to get value from decision matrix after optimization?
回答済みSuppose I have a matrix defined as follows:
MM = model.addVars(I, J, vtype=GRB.BINARY, name='MM')
...
model.optimize()
After Solution was found I want to save matrix MM as a 2D numpy array Result to use later in the code. Smth like: Result = [[1, 0, 0], [0, 1, 0], [0,1,0]] (where MM[1][1]=1 for example)
How can I do this in python?
0
-
You can get the optimal solution value by accessing the X attribute of a given variable.
The following code snippet shows an example of how to construct such a numpy array. Please note that it is probably not the most Pythonic way to achieve it. Maybe someone could provide a more Pythonic way.
import gurobipy as gp
from gurobipy import GRB
import numpy as np
m = gp.Model()
I = 3
J = 2
MM = m.addVars(I,J,vtype=GRB.BINARY, name="MM")
m.addConstr(MM[1,1] == 1)
m.setObjective(gp.quicksum(MM))
m.optimize()
array = np.array(0)
if m.SolCount > 0:
# get tupledict holding solution values
L = []
for i in range(I):
K = []
for j in range(J):
K.append(MM[i,j].X)
L.append(K)
array = np.array(L)
print(array)0
サインインしてコメントを残してください。
コメント
1件のコメント