0297 STATIC SOURCE EXCERPTS
Repository: https://github.com/pilancilab/cpal
Commit: 14c27c1a97756493738390775c1e4fe818d52935
Source lines are one-based; notebook cell indices are zero-based.
No author code was executed; no historical experiment or score was reproduced.

MEMBER README.md
SHA256 6fd93b74a256578ec5d8d819d924b4a39fb72ca0ef3ee025d908d91849c49637
Git blob 2ee9f91bdbbc355fa2f1751742bdecfa175ff97a
1: # Cutting-Plane Active Learning (CPAL)
2: 
3: Cutting-plane active learning is a novel active learning algorithm designed for supervised learning tasks using ReLU networks of arbitrary depths. This active learning scheme induces a gradient-free learning scheme and, to the best of our knowledge, is the first active learning algorithm as of date to have achieved theoretical convergence guarantees. 
4: 
5: 🔗 Paper link: [Active Learning of Deep Neural Networks via Gradient-Free Cutting Planes](https://arxiv.org/pdf/2410.02145?)
6: 
7: ![CPAL pipeline](documentation/cpal.png)
8: 
9: 🚨 ***Note:*** *This repository is under active development. This version is preliminary and subject to change.*
10: 
11: # Abstract
12: Active learning methods aim to improve sample complexity in machine learning. In this work, we investigate an active learning scheme via a novel gradient-free cutting-plane training method for ReLU networks of arbitrary depth and develop a convergence theory. 

MEMBER src/cpal/cpal.py
SHA256 6c823ea77050da62c3561afeeec1cbbc5ccd56fc877e07d7a811cf42a9798593
Git blob 877f030675f21c9df3ff245862ca001f02300f4f
12: # compute analytic center
13: def center(S, X, dmat, R=1, boxinit=False, reg=False, beta =1e-5, reg_value=2e-4):
14:     """S is list of affine inequalities described as tuple of LHS vector/matrix and RHS scalar/vector"""
15:     _, d = X.shape
16:     m=dmat.shape[1]
17:     s = cp.Variable(2*d*m)
18:     obj = 0 if boxinit else cp.log(R - cp.norm(s))
19:     constraints = []
20:     if reg:
21:         U = cp.reshape(s, (2*d, m), order='F')
22:         constraints = [beta*(cp.mixed_norm(U[:d].T,2,1)+cp.mixed_norm(U[d:].T,2,1)) <= reg_value]
23:     if len(S) > 0:
24:         obj += cp.sum([cp.log(rhs - lhs @ s) for lhs, rhs in S])
25: 
26:     prob = cp.Problem(cp.Maximize(obj), constraints)
27: 
28:     solvers = ['MOSEK', 'CLARABEL', 'GLPK', 'SCS', 'ECOS', 'OSQP']
29:     for solver in solvers:
30:         try:
31:             prob.solve(solver=solver, verbose=False) # Warm_start set false for now.
32:             if prob.status == cp.OPTIMAL:
33:                 print(f"Solver {solver} succeeded!")
34:                 return s.value  # Return the center (concatenated c' and c vector)
35:         except Exception:
36:             if prob.status == cp.INFEASIBLE:
37:                 print(f"Solver {solver} is infeasible.")
38:             else:
39:                 pass
40:     
41:         raise RuntimeError("All solvers failed to find an optimal solution.")             
42: 
43:     return s.value

MEMBER src/cpal/cpal.py
SHA256 6c823ea77050da62c3561afeeec1cbbc5ccd56fc877e07d7a811cf42a9798593
Git blob 877f030675f21c9df3ff245862ca001f02300f4f
44: 
45: def cut_reg(S, x, y, dmat_row, thresh): # cut for reg-cpal
46:     m = len(dmat_row)
47:     
48:     # Compute f^convex part
49:     f_convex = dmat_row @ np.kron(np.eye(m), np.concatenate((x, -x)).T)
50: 
51:     # Decompose the norm constraint into two linear constraints
52:     S.append((f_convex, y + thresh))  # First inequality: f_convex @ theta <= y + thresh
53:     S.append((-f_convex, -y + thresh))  # Second inequality: -f_convex @ theta <= -y + thresh
54: 
55:     # ReLU-based constraint
56:     relu_constraint = -np.kron(np.diag(2*dmat_row - np.ones(m)), np.kron(np.eye(2), x))
57:     for lhs in relu_constraint:
58:         S.append((lhs, 0))  # Append ReLU constraint to S
59: 
60: 
61: def cut_classification(S, x, y, dmat_row):
62:     m = len(dmat_row)
63:     S.append((-y * dmat_row @ np.kron(np.eye(m), np.concatenate((x, -x)).T), 0))
64: 
65:     relu_constraint = -np.kron(np.diag(2*dmat_row-np.ones(m)), np.kron(np.eye(2), x))
66:     for lhs in relu_constraint:
67:         S.append((lhs, 0))
68: 
69: 
70: def query(c, data_tried, data_used, X, dmat):
71:     n_train, _ = X.shape
72: 
73:     mini = np.inf
74:     i_mini = -1
75: 
76:     maxi = -np.inf
77:     i_maxi = -1
78: 
79:     minabs = np.inf
80:     i_minabs = -1
81: 
82:     for i in range(n_train): # search in finite data (D implicit) set to re-use dmat
83:         if i not in data_tried and i not in data_used:
84:             pred = pred_point(i, c, X, dmat)
85:             if pred < mini:
86:                 i_mini = 1*i
87:                 mini = pred
88:             if pred > maxi:
89:                 i_maxi = 1*i
90:                 maxi = pred
91:             if abs(pred) < minabs:
92:                 i_minabs = 1*i
93:                 minabs = abs(pred)
94: 
95:     return i_mini, i_maxi, i_minabs
96: 

MEMBER src/cpal/cpal.py
SHA256 6c823ea77050da62c3561afeeec1cbbc5ccd56fc877e07d7a811cf42a9798593
Git blob 877f030675f21c9df3ff245862ca001f02300f4f
119: 
120: # cutting-plane algorithm for classification and regression tasks
121: def cutting_plane(task, X, y, dmat, n_points=100, maxit=10000, R = 1, threshold = 1e-3, boxinit=False):
122:     _, d = X.shape
123:     m=dmat.shape[1]
124:     C0_lower = -R*np.ones(2*d*m)
125:     C0_upper = R*np.ones(2*d*m)
126: 
127:     data_tried = []
128:     data_used = []
129:     
130:     Ct = []
131:     if boxinit:
132:         for i, (l, u) in enumerate(zip(C0_lower, C0_upper)):
133:             one_vec = np.zeros(2*d*m)
134:             one_vec[i] = 1
135:             Ct.append((one_vec, u))
136:             Ct.append((-one_vec, -l))
137:     
138:     c = None
139:     did_cut = True
140:     it = 0
141: 
142:     while len(data_used) < n_points and it < maxit:
143:         if did_cut:
144:             c = center(Ct, dmat = dmat, X=X, R=R) # recompute center
145:             did_cut = False
146:         i_mini, i_maxi, _ = query(c, data_tried, data_used, X, dmat)
147:         if i_mini is None:
148:             return Ct, c, data_used
149:         data_tried += [i_mini, i_maxi]
150:         data_tried = list(set(data_tried))
151:         if task == 'c':
152:             if np.sign(pred_point(i_mini, c, X, dmat)) != y[i_mini]:
153:                 print(f'Cutting at iteration {it}')
154:                 cut_classification(Ct, X[i_mini], y[i_mini], dmat[i_mini])
155:                 data_used.append(i_mini)
156:                 did_cut = True
157:             if np.sign(pred_point(i_maxi, c, X, dmat)) != y[i_maxi]:
158:                 print(f'Cutting at iteration {it}')
159:                 cut_classification(Ct, X[i_maxi], y[i_maxi], dmat[i_maxi])
160:                 data_used.append(i_maxi)
161:                 did_cut = True
162:         elif task == 'r':
163:             if np.linalg.norm(pred_point(i_mini, c, X, dmat) - y[i_mini]) > threshold:
164:                 print(f'Cutting at iteration {it}')
165:                 cut_reg(Ct, X[i_mini], y[i_mini], dmat[i_mini],threshold)
166:                 data_used.append(i_mini)
167:                 did_cut = True
168:             if np.linalg.norm(pred_point(i_maxi, c, X, dmat)- y[i_maxi]) > threshold:
169:                 print(f'Cutting at iteration {it}')
170:                 cut_reg(Ct, X[i_maxi], y[i_maxi], dmat[i_maxi],threshold)
171:                 data_used.append(i_maxi)
172:                 did_cut = True
173:         else:
174:             raise ValueError("Task must be either 'c' for classification or 'r' for regression.")
175: 
176:         it += 1
177:     
178:     return Ct, c, data_used
179: 

MEMBER src/cpal/utils.py
SHA256 e994513b0930cb2b5e881c78f5620373125134b03b53ca647e759c687ae251a4
Git blob 49b33ee8c17058f7302972b991572116d59925bd
122: 
123: 
124: 
125: # --- Prediction and Constraint Functions for 2-layer CPAL ---
126: def pred_point(i, vec, X, dmat): # corresponds to <w(theta), x>
127:     return (dmat[i] @ np.kron(np.eye(len(dmat[i])), np.concatenate((X[i], -X[i])).T)) @ vec
128: 
129: def constraint(i, U1v, U2v, X, dmat):
130:     m = dmat.shape[1]
131:     var = np.vstack((U1v, U2v)).flatten(order='F')
132:     return np.kron(np.diag(2*dmat[i]-np.ones(m)), np.kron(np.eye(2), X[i])) @ var
133: 
134: # sampling function
135: def sample_classifier(Ct, c, maxiter=10**5):
136:     for _ in range(maxiter):
137:         candidate = c + np.random.randn(*c.shape)
138:         if in_Ct(candidate, Ct):
139:             return candidate
140:     print(f'Failed to sample after {maxiter} tries.')
141:     return None
142: 
143: def in_Ct(c, Ct, eps=1e-3):
144:     for lhs, rhs in Ct:
145:         if lhs @ c > rhs + eps:
146:             return False
147:     return True
148: 
149: 
150: # --- Prediction and Constraint Functions for 3-layer CPAL ---
151: def sort_center(X, c, Di, Qj):
152:     _, d = X.shape
153:     P2 = Di.shape[1]
154:     P1 = Qj.shape[1]
155:     c1 = {}; c2 = {}; c3 = {}; c4 = {}
156:     for i in range(P2):
157:         for j in range(P1):
158:             c1[(i,j)] = c[(d*P1*i+d*j):(d*P1*i+d*j+d)]
159:             c2[(i,j)] = c[(P2*P1*d+d*P1*i+d*j):(P2*P1*d+d*P1*i+d*j+d)]
160:             c3[(i,j)] = c[(P2*P1*2*d+d*P1*i+d*j):(P2*P1*2*d+d*P1*i+d*j+d)]
161:             c4[(i,j)] = c[(P2*P1*3*d+d*P1*i+d*j):(P2*P1*3*d+d*P1*i+d*j+d)]
162:     return c1, c2, c3, c4
163: 
164: def predict(X, c, i, Di, Qj):
165:     P2 = Di.shape[1]
166:     P1 = Qj.shape[1]
167:     c1, c2, c3, c4 = sort_center(X, c, Di, Qj)
168:     xa = X[i,:]
169:     pred = 0
170:     for l in range(P2):
171:         sum_pos = 0
172:         sum_neg = 0
173:         for j in range(P1):
174:             sum_pos += Qj[i,j]*(xa@c1[(l,j)])-Qj[i,j]*(xa@c2[(l,j)])
175:             sum_neg += Qj[i,j]*(xa@c3[(l,j)])-Qj[i,j]*(xa@c4[(l,j)])
176:         pred += Di[i,j]*sum_pos - Di[i,j]*sum_neg
177:     return pred
178: 

MEMBER src/cpal/cpal_3layer.py
SHA256 27c023d1c5282a6d1871ae4c686f6ee8b7adeddcc37e898138ff817dfa9fcb97
Git blob 8e21d115642b0e6830a103e8d69610cbfb468953
26: def cut(X, y, S, i, Di, Qj):
27:     P2 = Di.shape[1]
28:     P1 = Qj.shape[1]
29:     # inner relu constraint 
30:     i1 = np.kron(np.diag(2*Qj[i,:]-1),X[i,:])
31:     i2 = np.kron(np.eye(4*P2),i1)
32:     S.append((-i2,0))
33:     # outter relu constraint 
34:     o1 = np.kron(Qj[i,:],X[i,:])
35:     o2 = np.kron(np.diag(2*Di[i,:]-1), o1)
36:     o3 = np.kron(np.array([1,-1]),o2)
37:     o4 = np.kron(np.eye(2),o3)
38:     S.append((-o4,0))
39:     # prediction constraint 
40:     p1 = np.kron(Qj[i,:],X[i,:])
41:     p2 = np.kron(np.diag(Di[i,:]), p1)
42:     p3 = np.kron(np.array([1,-1,-1,1]),p2)
43:     S.append((-y[i]*(p3.sum(axis=0)),0))
44: 
45: def query(X, c, Di, Qj, data_used, data_tried):
46:     n_train, _ = X.shape
47:     mini = np.inf
48:     i_mini = -1
49:     maxi = -np.inf
50:     i_maxi = -1
51:     minabs = np.inf
52:     i_minabs = -1
53:     for i in range(n_train): 
54:         if (i not in data_used) and (i not in data_tried):
55:             pred = predict(X, c, i, Di, Qj)
56:             if pred < mini:
57:                 i_mini = 1*i
58:                 mini = pred
59:             if pred > maxi:
60:                 i_maxi = 1*i
61:                 maxi = pred
62:             if abs(pred) < minabs:
63:                 i_minabs = 1*i
64:                 minabs = abs(pred) 
65:     return i_mini, i_maxi, i_minabs
66: 
67: 
68: def cutting_plane_3layer(X, y, Di, Qj, n_points):
69:     n_train, _ = X.shape
70:     data_used = []
71:     data_tried = []
72:     plane = []
73:     it = 0
74:     while len(data_used) < n_train and it < n_points:
75:         c = center(X, plane, Di, Qj)
76:         i_mini, i_maxi, _ = query(X, c, Di, Qj, data_used, data_tried)
77:         data_tried += [i_mini, i_maxi]
78:         if np.sign(predict(X, c, i_mini, Di, Qj)) != y[i_mini]:
79:             cut(X, y, plane,i_mini, Di, Qj)
80:             data_used.append(i_mini)
81:         if np.sign(predict(X, c, i_maxi, Di, Qj)) != y[i_maxi]:
82:             cut(X,y, plane, i_maxi, Di, Qj)
83:             data_used.append(i_maxi)
84:         it += 1     
85:         print('cutting plane iteration: ', it, ' # data used: ', data_used)    
86:     return c, data_used

MEMBER src/apps/sentiment_classification.py
SHA256 0a444d6e89b3403674c670bb7739842828ef1d578a8b5a2201bb430b222e57a7
Git blob dd0da6c30f9b9a3c5a2ed3a357fdaa4a459b3b93
53: imdb_test_sentence_embeddings = imdb_test_masked_word_embeddings[torch.arange(N_test),(torch.count_nonzero(imdb_test_attention_mask,dim=1)-2).long(),:]
54: 
55: 
56: Xtrain = imdb_train_sentence_embeddings[:,0:200]
57: Xtest = imdb_test_sentence_embeddings[:,0:200]
58: 
59: 
60: Xtrain = Xtrain[:,0:200]
61: Xtest = Xtest[:,0:200]
62: 

MEMBER src/apps/sentiment_classification.py
SHA256 0a444d6e89b3403674c670bb7739842828ef1d578a8b5a2201bb430b222e57a7
Git blob dd0da6c30f9b9a3c5a2ed3a357fdaa4a459b3b93
113: def pred_point_simplified_vec(i, vec):
114:     return (dmat[i] @ torch.kron(torch.eye(len(dmat[i])).to(device), torch.concatenate((Xtrain[i], -Xtrain[i])).T).to(device)) @ vec
115: 
116: def cut(S, x, y, dmat_row):
117:     m = len(dmat_row)
118:     S.append(((-y * dmat_row @ torch.kron(torch.eye(m).to(device), torch.concatenate((x, -x)).T)).cpu().detach().numpy(), 0))
119:     
120:     relu_constraint = -torch.kron(torch.diag(2*dmat_row-torch.ones(m).to(device)), torch.kron(torch.eye(2).to(device), x)).cpu().detach().numpy()
121:     for lhs in relu_constraint:
122:         S.append((lhs , 0))
123: 
124: def query(c, data_tried, data_used, M=100, iter=0):

MEMBER src/apps/sentiment_classification.py
SHA256 0a444d6e89b3403674c670bb7739842828ef1d578a8b5a2201bb430b222e57a7
Git blob dd0da6c30f9b9a3c5a2ed3a357fdaa4a459b3b93
150:     data_used = []
151:     Ct = []
152:     c = None
153:     did_cut = True
154:     it = 0
155:     while len(data_used) < n_points and it < maxit:
156:         if len(data_tried) == N:
157:             data_tried = []
158:         if did_cut:
159:             try:
160:                 c = torch.Tensor(center(Ct, R=R)).to(device)
161:             except:
162:                 print('solver ERROR')
163:                 pass
164:             did_cut = False
165:         i_mini, i_maxi, i_minabs = query(c, data_tried, data_used,iter=it)
166:         data_tried += [i_minabs] 
167:         data_tried = list(set(data_tried))
168:         theta_matrix = c.reshape((2*d, m))
169:         v1_list = theta_matrix[:d]; v2_list = theta_matrix[d:]
170:         ytest_cvx=torch.sign(torch.sum(drelu(Xtest@v1_list)*(Xtest@v1_list)-drelu(Xtest@v2_list)*(Xtest@v2_list),axis=1)).to(device)
171:         ytrain_cvx=torch.sign(torch.sum(drelu(Xtrain@v1_list)*(Xtrain@v1_list)-drelu(Xtrain@v2_list)*(Xtrain@v2_list),axis=1)).to(device)
172:         print(f'iter: {it}','convex test accuracy: ', torch.sum(ytest_cvx == ytest) / len(ytest),' #points: ', len(data_used))
173:         ytest_twolayer = ((torch.sigmoid(twolayer_nn(Xtest)))>0.5).int()*2-1
174:         print(f'iter: {it}','twolayer test accuracy: ', torch.sum(ytest_twolayer.squeeze() == ytest) / len(ytest))
175:         if len(score)==0:
176:             score.append((torch.sum(ytest_cvx == ytest) / len(ytest), len(data_used)))
177:         else:
178:             if len(data_used)==score[-1][1]:
179:                 pass 
180:             else:
181:                 score.append((torch.sum(ytest_cvx == ytest) / len(ytest), len(data_used)))
182:         if True: 
183:             print(f'{i_minabs=},{len(data_tried)=},{len(data_used)=}')
184:             if torch.sign(pred_point_simplified_vec(i_minabs, c)) != ytrain[i_minabs]:
185:                 if i_minabs not in data_used:
186:                     # convex cut 
187:                     print(f'Cutting at iteration {it}, index {i_minabs}')
188:                     cut(Ct, Xtrain[i_minabs], ytrain[i_minabs], dmat[i_minabs])
189:                     data_used.append(i_minabs)
190:                     did_cut = True
191: 
192:                     # non-convex update 
193:                     twolayer_pred = torch.sigmoid(twolayer_nn(Xtrain[i_minabs]))
194:                     y_revise = (ytrain[i_minabs]+1)/2
195:                     loss = -(y_revise*torch.log(twolayer_pred)+(1-y_revise)*torch.log(1-twolayer_pred))
196:                     twolayer_nn.zero_grad()
197:                     loss.backward()
198:                     with torch.no_grad():
199:                         for name, param in twolayer_nn.named_parameters():
200:                             if param.requires_grad:
201:                                 param.data -= learning_rate * param.grad

MEMBER examples/cpal_classification.ipynb
SHA256 d2216daa354130218da42986a14a55b50292a1ea7df8b6b348a85222e22e9820
Git blob c8aac2243942fdeedfdfd99993e8dc25d73e65a6
CELL 8
1: C, c, used = cutting_plane('c',X, y, dmat, n_points = 20)
2: print(f'used: {used}')
CELL 9
1: n_train, m = dmat.shape
2: d = X.shape[1]
3: theta_matrix = np.reshape(c, (2*d,m), order ='F') # the resulting theta_matrix is of shape (2d, m)
4: Uopt1_v = theta_matrix[:d]
5: Uopt2_v = theta_matrix[d:]
6: # do the final convex solve
7: Uopt1_final_v, Uopt2_final_v, _ = convex_solve(used, X, y, dmat)
CELL 19
1: deepal_selected_indices = []
2: deepal_strategies = ["RandomSampling", "LeastConfidence", "EntropySampling","KMeansSampling", "BALDDropout"]
3: 
4: 
5: for al in deepal_strategies:
6:     args = SimpleNamespace(
7:         seed=1,
8:         n_init_labeled=1,
9:         n_query=1,
10:         n_round=14,
11:         dataset_name='Spiral',
12:         strategy_name=al,
13:         save_dir="class_plots",
14:         save_pickle="class_accuracy"
15:     )
16: 
17:     selected_indices, rmse_train, rmse_test, strategy, dataset, net, device = run_active_learning(args)
18:     deepal_selected_indices.append(selected_indices)

MEMBER examples/cpal_3layer.ipynb
SHA256 bae91887492205f71608737d5ba88e5b04cb780e1bad562876eef37f2d3114d5
Git blob 3f53464ee63eaf149fa4b80474dda80cd7d07906
CELL 3
1: P2 = 100; P1 = 50
2: Di, Qj = generate_3layer_hyperplane_arrangement(X, P1, P2)
3: P2 = Di.shape[1]
4: P1 = Qj.shape[1]
5: print(f'{P2=},{P1=}')
CELL 5
1: center, used = cutting_plane_3layer(X, y, Di, Qj, 20)

