Debian Codegraph @

test/automatic/svm/svm-original.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 def subgradient(self, wb, X, y):
84 """Compute the subgradient of the objective function.
85
86 Arguments:
87 wb (ndarray, shape = (n_features+1,)):
88 concatenation of the weight vector with the bias wb=[w,b]
89 X (ndarray, shape = (n_samples, n_features)):
90 Training input matrix where each row is a feature vector.
91 The data in X are passed in without a bias column!
92 y (ndarray, shape = (n_samples,)):
93 Training target. Each entry is either -1 or 1.
94
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
103 w = wb[:-1]
104 b = wb[-1]
105
106 subgrad = np.zeros(n_features + 1)
107 for i in range(n_features):
108 for n in range(n_samples):
109 subgrad[i] += (
110 (-y[n] * X[n][i]) if y[n] * (np.dot(X[n], w) + b) < 1 else 0
111 )
112 subgrad[i] += (
113 self.lambda1 * (-1 if w[i] < 0 else 1) + 2 * self.lambda2 * w[i]
114 )
115
116 for n in range(n_samples):
117 subgrad[-1] += -y[n] if y[n] * (np.dot(X[n], w) + b) < 1 else 0
118
119 return subgrad
120
121 def get_params(self):
122 return (self.w, self.b)
123
124
125 def main():
126 with open("data/svm_data.pkl", "rb") as f:
127 train_X, train_y, test_X, test_y = pickle.load(f)
128
129 model = SVM()
130 model.fit(train_X, train_y, iterations=500, disp=1)
131 print(model.get_params())
132
133
134 if __name__ == "__main__":
135 main()