Debian Codegraph @

test/automatic/svm/svm-optimized.py

raw symbols SCIP
1 import math
2 import pickle
3 import numpy as np
4 from numpy import linalg as LA
5
6 np.random.seed(1)
7
8
9 class SVM:
10 """SVC with subgradient descent training.
11
12 Arguments:
13 lambda1: regularization parameter for L1 regularization (default: 1)
14 lambda2: regularization parameter for L2 regularization (default: 1)
15 iterations: number of training iterations (default: 500)
16 """
17
18 def __init__(self, lambda1=1, lambda2=1):
19 self.lambda1 = lambda1
20 self.lambda2 = lambda2
21
22 def fit(self, X, y, iterations=500, disp=-1):
23 """Fit the model using the training data.
24
25 Arguments:
26 X (ndarray, shape = (n_samples, n_features)):
27 Training input matrix where each row is a feature vector.
28 The data in X are passed in without a bias column!
29 y (ndarray, shape = (n_samples,)):
30 Training target. Each entry is either -1 or 1.
31
32 Notes: This function must set member variables such that a subsequent call
33 to get_params or predict uses the learned parameters, overwriting
34 any parameter values previously set by calling set_params.
35
36 """
37 n_features = X.shape[1]
38
39 x = np.random.rand(n_features + 1)
40 minimizer = x
41 fmin = self.objective(x, X, y)
42
43 for t in range(iterations):
44 if disp != -1 and t % disp == 0:
45 print("At iteration", t, "f(minimizer) =", fmin)
46 alpha = 0.002 / math.sqrt(t + 1)
47 subgrad = self.subgradient(x, X, y)
48 x -= alpha * subgrad
49 objective = self.objective(x, X, y)
50 if objective < fmin:
51 fmin = objective
52 minimizer = x
53
54 self.w = minimizer[:-1]
55 self.b = minimizer[-1]
56
57 def objective(self, wb, X, y):
58 """Compute the objective function for the SVM.
59
60 Arguments:
61 wb (ndarray, shape = (n_features+1,)):
62 concatenation of the weight vector with the bias wb=[w,b]
63 X (ndarray, shape = (n_samples, n_features)):
64 Training input matrix where each row is a feature vector.
65 The data in X are passed in without a bias column!
66 y (ndarray, shape = (n_samples,)):
67 Training target. Each entry is either -1 or 1.
68
69 Returns:
70 obj (float): value of the objective function evaluated on X and y.
71 """
72 n_samples = X.shape[0]
73
74 w = wb[:-1]
75 b = wb[-1]
76
77 sum = 0
78 for n in range(n_samples):
79 sum += max(0, 1 - y[n] * (np.dot(X[n], w) + b))
80
81 return sum + self.lambda1 * LA.norm(w, 1) + self.lambda2 * (LA.norm(w, 2) ** 2)
82
83 # Proposed optimization:
84 # This code has been optimized by replacing the for loops with vectorized operations. This reduces the time complexity from O(n^2) to O(n), resulting in a substantial speedup.
85 def subgradient(self, wb, X, y):
86 """Compute the subgradient of the objective function.
87 Arguments:
88 wb (ndarray, shape = (n_features+1,)):
89 concatenation of the weight vector with the bias wb=[w,b]
90 X (ndarray, shape = (n_samples, n_features)):
91 Training input matrix where each row is a feature vector.
92 The data in X are passed in without a bias column!
93 y (ndarray, shape = (n_samples,)):
94 Training target. Each entry is either -1 or 1.
95 Returns:
96 subgrad (ndarray, shape = (n_features+1,)):
97 subgradient of the objective function with respect to
98 the coefficients wb=[w,b] of the linear model
99 """
100 n_samples = X.shape[0]
101 n_features = X.shape[1]
102 w = wb[:-1]
103 b = wb[-1]
104 # Vectorized operations to replace for loops
105 subgrad = np.zeros(n_features + 1)
106 subgrad[:-1] = np.sum(
107 -y[:, None] * X * (y * (X.dot(w) + b) < 1)[:, None], axis=0
108 )
109 subgrad[:-1] += self.lambda1 * np.sign(w) + 2 * self.lambda2 * w
110 subgrad[-1] = np.sum(-y * (y * (X.dot(w) + b) < 1))
111 return subgrad
112
113 def subgradient_orig(self, wb, X, y):
114 """Compute the subgradient of the objective function.
115
116 Arguments:
117 wb (ndarray, shape = (n_features+1,)):
118 concatenation of the weight vector with the bias wb=[w,b]
119 X (ndarray, shape = (n_samples, n_features)):
120 Training input matrix where each row is a feature vector.
121 The data in X are passed in without a bias column!
122 y (ndarray, shape = (n_samples,)):
123 Training target. Each entry is either -1 or 1.
124
125 Returns:
126 subgrad (ndarray, shape = (n_features+1,)):
127 subgradient of the objective function with respect to
128 the coefficients wb=[w,b] of the linear model
129 """
130 n_samples = X.shape[0]
131 n_features = X.shape[1]
132
133 w = wb[:-1]
134 b = wb[-1]
135
136 subgrad = np.zeros(n_features + 1)
137 for i in range(n_features):
138 for n in range(n_samples):
139 subgrad[i] += (
140 (-y[n] * X[n][i]) if y[n] * (np.dot(X[n], w) + b) < 1 else 0
141 )
142 subgrad[i] += (
143 self.lambda1 * (-1 if w[i] < 0 else 1) + 2 * self.lambda2 * w[i]
144 )
145
146 for n in range(n_samples):
147 subgrad[-1] += -y[n] if y[n] * (np.dot(X[n], w) + b) < 1 else 0
148
149 return subgrad
150
151 def get_params(self):
152 return (self.w, self.b)
153
154
155 def main():
156 with open("data/svm_data.pkl", "rb") as f:
157 train_X, train_y, test_X, test_y = pickle.load(f)
158
159 model = SVM()
160 model.fit(train_X, train_y, iterations=500, disp=1)
161 print(model.get_params())
162
163
164 if __name__ == "__main__":
165 main()