-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathgrad_hinge.py
185 lines (146 loc) · 6.08 KB
/
grad_hinge.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
import numpy as np
import pdb
from scipy import sparse
from scipy.optimize import fmin_ncg
import pdb
import time
# for hinge loss SVM
def hessian_vector_product_hinge(label, ypred, x, v, scale_factor=1.0):
mask = np.ones_like(label)
mask[ypred * label >= 1] = 0
mask[ypred * label <= 0] = 0
t = label * mask
xv = x.dot(v)
txv = t.dot(xv)
hvp = txv * x.T.dot(t)
hvp = hvp / x.shape[0] * scale_factor
return hvp
def hessian_hingle_loss_theta(label, ypred, x):
mask = np.ones_like(label)
mask[ypred * label >= 1] = 0
mask[ypred * label <= 0] = 0
t = label * mask
tx = x.T.dot(t.reshape(-1,1))
txxt = tx.dot(tx.T)
return txxt
def batch_grad_hinge_loss(label, ypred, x):
if not isinstance(x, sparse.csr_matrix):
x = sparse.csr_matrix(x)
mask_1 = np.zeros_like(ypred)
mask_1[ypred * label <= 0] = 1
mask_1 = mask_1.astype(int)
mask_2 = np.logical_xor(np.ones_like(mask_1), mask_1).astype(int)
mask_3 = np.ones_like(mask_1)
mask_3[ypred * label > 1] = 0
mask_3 = mask_3.astype(int)
val_1 = -x.multiply(label.reshape(-1,1))
val_2 = -val_1.multiply((1-label*ypred).reshape(-1,1))
# val_1 = np.asarray(val_1.mean(0)).flatten()
# val_2 = np.asarray(val_2.mean(0)).flatten()
val_1 = val_1.multiply(mask_1.reshape(-1,1))
val_2 = val_2.multiply(mask_2.reshape(-1,1))
val_1 = val_1.multiply(mask_3.reshape(-1,1))
val_2 = val_2.multiply(mask_3.reshape(-1,1))
grad = val_1 + val_2
return grad
def grad_hinge_loss_theta(label, ypred, x):
if not isinstance(x, sparse.csr_matrix):
x = sparse.csr_matrix(x)
mask_1 = np.zeros_like(ypred)
mask_1[ypred * label <= 0] = 1
mask_1 = mask_1.astype(int)
mask_2 = np.logical_xor(np.ones_like(mask_1), mask_1).astype(int)
mask_3 = np.ones_like(mask_1)
mask_3[ypred * label > 1] = 0
mask_3 = mask_3.astype(int)
val_1 = -x.multiply(label.reshape(-1,1))
val_2 = -val_1.multiply((1-label*ypred).reshape(-1,1))
# val_1 = np.asarray(val_1.mean(0)).flatten()
# val_2 = np.asarray(val_2.mean(0)).flatten()
val_1 = val_1.multiply(mask_1.reshape(-1,1))
val_2 = val_2.multiply(mask_2.reshape(-1,1))
val_1 = val_1.multiply(mask_3.reshape(-1,1))
val_2 = val_2.multiply(mask_3.reshape(-1,1))
grad = np.asarray((val_1 + val_2).mean(0)).flatten()
return grad
def inverse_hvp_hinge_newtonCG(x_train,y_train,y_pred,v,hessian_free=True,tol=1e-5, scale_factor=1.0):
"""Get inverse hessian-vector-products H^-1 * v, this method is not suitable for
the large dataset.
Args:
x_train, y_train: training data used for computing the hessian, e.g. x_train: [None,n]
y_pred: predictions made on x_train, e.g. [None,]
v: value vector, e.g. [n,]
hessian_free: bool, `True` means use implicit hessian-vector-product to avoid
building hessian directly, `False` will build hessian.
hessian free will save memory while be slower in computation, vice versa.
such that set `True` when cope with large dataset, and set `False` with
relatively small dataset.
Return:
H^-1 * v: shape [None,]
"""
if not hessian_free:
hessian_matrix = hessian_hingle_loss_theta(y_train,y_pred,x_train,scale_factor)
# build functions for newton-cg optimization
def fmin_loss_fn(x):
"""Objective function for newton-cg.
H^-1 * v = argmin_t {0.5 * t^T * H * t - v^T * t}
"""
if hessian_free:
hessian_vec_val = hessian_vector_product_hinge(y_train,y_pred,x_train,x,scale_factor) # [n,]
else:
hessian_vec_val = np.dot(x,hessian_matrix) # [n,]
obj = 0.5 * np.dot(hessian_vec_val,x) - \
np.dot(x, v)
return obj
def fmin_grad_fn(x):
"""Gradient of the objective function w.r.t t:
grad(obj) = H * t - v
"""
if hessian_free:
hessian_vec_val = hessian_vector_product_hinge(y_train,y_pred,x_train,x,scale_factor)
else:
hessian_vec_val = np.dot(x,hessian_matrix) # [n,]
grad = hessian_vec_val - v
return grad
def get_fmin_hvp(x,p):
# get H * p
if hessian_free:
hessian_vec_val = hessian_vector_product_hinge(y_train,y_pred,x_train,p,scale_factor)
else:
hessian_vec_val = np.dot(p,hessian_matrix)
return hessian_vec_val
def get_cg_callback(verbose):
def fmin_loss_split(x):
if hessian_free:
hessian_vec_val = hessian_vector_product_hinge(y_train,y_pred,x_train,x,scale_factor)
else:
hessian_vec_val = np.dot(x,hessian_matrix)
loss_1 = 0.5 * np.dot(hessian_vec_val,x)
loss_2 = - np.dot(v, x)
return loss_1, loss_2
def cg_callback(x):
# idx_to_remove = 5
# xs = x_train[idx_to_remove]
# label = y_train[idx_to_remove]
# ys = y_pred[idx_to_remove]
# train_grad_loss_val = grad_logloss_theta_lr(label,ys,xs.reshape(1,-1))
# predicted_loss_diff = np.dot(x,train_grad_loss_val) / x_train.shape[0]
if verbose:
print("Function value:", fmin_loss_fn(x))
quad, lin = fmin_loss_split(x)
print("Split function value: {}, {}".format(quad, lin))
# print("Predicted loss diff on train_idx {}: {}".format(idx_to_remove, predicted_loss_diff))
return cg_callback
start_time = time.time()
cg_callback = get_cg_callback(verbose=True)
fmin_results = fmin_ncg(f=fmin_loss_fn,
x0=v,
fprime=fmin_grad_fn,
fhess_p=get_fmin_hvp,
callback=cg_callback,
avextol=tol,
maxiter=100,)
print("implicit hessian-vector products mean:",fmin_results.mean())
print("implicit hessian-vector products norm:",np.linalg.norm(fmin_results))
print("Inverse HVP took {:.1f} sec".format(time.time() - start_time))
return fmin_results