-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
76 lines (59 loc) · 1.8 KB
/
test.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
import numpy as np
import scipy.optimize as opt
# All data
points = [
[np.array([0, 0], dtype=np.float64), -1.0],
[np.array([5, 5], dtype=np.float64), 1.0],
[np.array([1, 0], dtype=np.float64), -1.0],
[np.array([0, 1], dtype=np.float64), -1.0],
[np.array([0, -1], dtype=np.float64), -1.0],
[np.array([-1, 0], dtype=np.float64), -1.0],
[np.array([3, -1], dtype=np.float64), 1.0],
[np.array([3, 1], dtype=np.float64), 1.0],
[np.array([6, 1], dtype=np.float64), 1.0],
[np.array([6, -1], dtype=np.float64), 1.0],
]
# Define the function to minimize
def dual(u):
sum = 0.0
for i in range(len(points)):
sum += u[i]
sum_in_sum = 0.0
for i in range(len(points)):
for j in range(len(points)):
sum_in_sum += (
points[i][1]
* points[j][1]
* u[i]
* u[j]
* np.dot(points[i][0], points[j][0])
)
return -(sum - 0.5 * sum_in_sum)
def con(u):
sum = 0.0
for i in range(len(points)):
sum += points[i][1] * u[i]
return sum
cons = [{"type": "eq", "fun": con}]
# Find the minimum value of the function
result = opt.minimize(
dual,
x0=[100 for _ in range(len(points))],
bounds=[(0, 500) for _ in range(len(points))],
# method="BFGS",
constraints=cons,
)
mu = result.x
print(f"mu = {mu}")
w = np.array([0 for _ in range(len(points[0][0]))], dtype=np.float64)
for i in range(len(mu)):
w += points[i][1] * mu[i] * points[i][0]
print(f"w = {w}")
chosen_mu = 0.0
chosen_mu_index = -1
for i in range(len(points)):
if mu[i] > chosen_mu:
chosen_mu = mu[i]
chosen_mu_index = i
b = -(np.dot(w, points[chosen_mu_index][0]) - points[chosen_mu_index][1])
print(f"{round(w[0], 5)}x + {round(w[1], 5)}y + {round(b, 5)}")