forked from LeviCC8/Explications-ANNs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
milp.py
226 lines (179 loc) · 8.08 KB
/
milp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import docplex.mp.model as mp
from cplex import infinity
import numpy as np
import tensorflow as tf
import pandas as pd
def codify_network_fischetti(mdl, layers, input_variables, auxiliary_variables, intermediate_variables, decision_variables, output_variables):
output_bounds = []
for i in range(len(layers)):
A = layers[i].get_weights()[0].T
b = layers[i].bias.numpy()
x = input_variables if i == 0 else intermediate_variables[i-1]
if i != len(layers) - 1:
s = auxiliary_variables[i]
a = decision_variables[i]
y = intermediate_variables[i]
else:
y = output_variables
for j in range(A.shape[0]):
if i != len(layers) - 1:
mdl.add_constraint(A[j, :] @ x + b[j] == y[j] - s[j], ctname=f'c_{i}_{j}')
mdl.add_indicator(a[j], y[j] <= 0, 1)
mdl.add_indicator(a[j], s[j] <= 0, 0)
mdl.maximize(y[j])
mdl.solve()
ub_y = mdl.solution.get_objective_value()
mdl.remove_objective()
mdl.maximize(s[j])
mdl.solve()
ub_s = mdl.solution.get_objective_value()
mdl.remove_objective()
y[j].set_ub(ub_y)
s[j].set_ub(ub_s)
else:
mdl.add_constraint(A[j, :] @ x + b[j] == y[j], ctname=f'c_{i}_{j}')
mdl.maximize(y[j])
mdl.solve()
ub = mdl.solution.get_objective_value()
mdl.remove_objective()
mdl.minimize(y[j])
mdl.solve()
lb = mdl.solution.get_objective_value()
mdl.remove_objective()
y[j].set_ub(ub)
y[j].set_lb(lb)
output_bounds.append([lb, ub])
return mdl, output_bounds
def codify_network_tjeng(mdl, layers, input_variables, intermediate_variables, decision_variables, output_variables):
output_bounds = []
for i in range(len(layers)):
A = layers[i].get_weights()[0].T
b = layers[i].bias.numpy()
x = input_variables if i == 0 else intermediate_variables[i-1]
if i != len(layers) - 1:
a = decision_variables[i]
y = intermediate_variables[i]
else:
y = output_variables
for j in range(A.shape[0]):
mdl.maximize(A[j, :] @ x + b[j])
mdl.solve()
ub = mdl.solution.get_objective_value()
mdl.remove_objective()
if ub <= 0 and i != len(layers) - 1:
print('ENTROU, o ub é negativo, logo y = 0')
mdl.add_constraint(y[j] == 0, ctname=f'c_{i}_{j}')
continue
mdl.minimize(A[j, :] @ x + b[j])
mdl.solve()
lb = mdl.solution.get_objective_value()
mdl.remove_objective()
if lb >= 0 and i != len(layers) - 1:
print('ENTROU, o lb >= 0, logo y = Wx + b')
mdl.add_constraint(A[j, :] @ x + b[j] == y[j], ctname=f'c_{i}_{j}')
continue
if i != len(layers) - 1:
mdl.add_constraint(y[j] <= A[j, :] @ x + b[j] - lb * (1 - a[j]))
mdl.add_constraint(y[j] >= A[j, :] @ x + b[j])
mdl.add_constraint(y[j] <= ub * a[j])
#mdl.maximize(y[j])
#mdl.solve()
#ub_y = mdl.solution.get_objective_value()
#mdl.remove_objective()
#y[j].set_ub(ub_y)
else:
mdl.add_constraint(A[j, :] @ x + b[j] == y[j])
#y[j].set_ub(ub)
#y[j].set_lb(lb)
output_bounds.append([lb, ub])
return mdl, output_bounds
def codify_network(model, dataframe, method, relaxe_constraints):
layers = model.layers
num_features = layers[0].get_weights()[0].shape[0]
mdl = mp.Model()
domain_input, bounds_input = get_domain_and_bounds_inputs(dataframe)
bounds_input = np.array(bounds_input)
if relaxe_constraints:
input_variables = mdl.continuous_var_list(num_features, lb=bounds_input[:, 0], ub=bounds_input[:, 1], name='x')
else:
input_variables = []
for i in range(len(domain_input)):
lb, ub = bounds_input[i]
if domain_input[i] == 'C':
input_variables.append(mdl.continuous_var(lb=lb, ub=ub, name=f'x_{i}'))
elif domain_input[i] == 'I':
input_variables.append(mdl.integer_var(lb=lb, ub=ub, name=f'x_{i}'))
elif domain_input[i] == 'B':
input_variables.append(mdl.binary_var(name=f'x_{i}'))
intermediate_variables = []
auxiliary_variables = []
decision_variables = []
for i in range(len(layers)-1):
weights = layers[i].get_weights()[0]
intermediate_variables.append(mdl.continuous_var_list(weights.shape[1], lb=0, name='y', key_format=f"_{i}_%s"))
if method == 'fischetti':
auxiliary_variables.append(mdl.continuous_var_list(weights.shape[1], lb=0, name='s', key_format=f"_{i}_%s"))
if relaxe_constraints and method == 'tjeng':
decision_variables.append(mdl.continuous_var_list(weights.shape[1], name='a', lb=0, ub=1, key_format=f"_{i}_%s"))
else:
decision_variables.append(mdl.binary_var_list(weights.shape[1], name='a', lb=0, ub=1, key_format=f"_{i}_%s"))
output_variables = mdl.continuous_var_list(layers[-1].get_weights()[0].shape[1], lb=-infinity, name='o')
if method == 'tjeng':
mdl, output_bounds = codify_network_tjeng(mdl, layers, input_variables,
intermediate_variables, decision_variables, output_variables)
else:
mdl, output_bounds = codify_network_fischetti(mdl, layers, input_variables, auxiliary_variables,
intermediate_variables, decision_variables, output_variables)
if relaxe_constraints:
# Tighten domain of variables 'a'
for i in decision_variables:
for a in i:
a.set_vartype('Integer')
# Tighten domain of input variables
for i, x in enumerate(input_variables):
if domain_input[i] == 'I':
x.set_vartype('Integer')
elif domain_input[i] == 'B':
x.set_vartype('Binary')
elif domain_input[i] == 'C':
x.set_vartype('Continuous')
return mdl, output_bounds
def get_domain_and_bounds_inputs(dataframe):
domain = []
bounds = []
for column in dataframe.columns[:-1]:
if len(dataframe[column].unique()) == 2:
domain.append('B')
bound_inf = dataframe[column].min()
bound_sup = dataframe[column].max()
bounds.append([bound_inf, bound_sup])
elif np.any(dataframe[column].unique().astype(np.int64) != dataframe[column].unique().astype(np.float64)):
domain.append('C')
bound_inf = dataframe[column].min()
bound_sup = dataframe[column].max()
bounds.append([bound_inf, bound_sup])
else:
domain.append('I')
bound_inf = dataframe[column].min()
bound_sup = dataframe[column].max()
bounds.append([bound_inf, bound_sup])
return domain, bounds
if __name__ == '__main__':
path_dir = 'glass'
#model = tf.keras.models.load_model(f'datasets\\{path_dir}\\model_{path_dir}.h5')
model = tf.keras.models.load_model(f'datasets\\{path_dir}\\teste.h5')
data_test = pd.read_csv(f'datasets\\{path_dir}\\test.csv')
data_train = pd.read_csv(f'datasets\\{path_dir}\\train.csv')
data = data_train.append(data_test)
data = data[['RI', 'Na', 'target']]
mdl, bounds = codify_network(model, data, 'tjeng', False)
print(mdl.export_to_string())
print(bounds)
# X ---- E
# x1 == 1 /\ x2 == 3 /\ F /\ ~E INSATISFÁTIVEL
# x1 >= 0 /\ x1 <= 100 /\ x2 == 3 /\ F /\ ~E INSATISFÁTIVEL -> x1 n é relevante, SATISFÁTIVEL -> x1 é relevante
'''
print("\n\nSolving model....\n")
msol = mdl.solve(log_output=True)
print(mdl.get_solve_status())
'''