-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsvm.py
More file actions
executable file
·51 lines (37 loc) · 1.15 KB
/
svm.py
File metadata and controls
executable file
·51 lines (37 loc) · 1.15 KB
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
#!/usr/bin/python
from gurobipy import *
x = [ [0,1], [1, 2], [3, 4]]
y = [ [1,1], [2,2], [4,4]]
gamma = 0.1
def optimize(x, y, gamma):
m = Model()
a = [ m.addVar(lb=-GRB.INFINITY, ub=GRB.INFINITY, name="a0"),
m.addVar(lb=-GRB.INFINITY, ub=GRB.INFINITY, name="a1") ]
beta = m.addVar(lb=-GRB.INFINITY, ub=GRB.INFINITY, name="beta")
u = []
N = len(x)
for i in xrange(N):
u.append(m.addVar(name=("u%d" % i)))
v = []
M = len(y)
for i in xrange(M):
v.append(m.addVar(name=("v%d" % i)))
m.update()
m.setObjective(a[0]*a[0] + a[1]*a[1] + gamma*(quicksum(u) + quicksum(v)))
for i in xrange(N):
xi = x[i]
m.addConstr(a[0]*xi[0] + a[1]*xi[1] - beta >= 1 - u[i], name=("x%d" % i))
for i in xrange(M):
yi = y[i]
m.addConstr(a[0]*yi[0] + a[1]*yi[1] - beta <= -(1 - v[i]), name=("y%d" % i))
m.update()
m.write('test.lp')
m.optimize()
results = {}
if m.Status == GRB.OPTIMAL:
results['a'] = [a[0].X, a[1].X]
results['beta'] = beta.X
return results
if __name__ == '__main__':
results = optimize(x, y, gamma)
print results