-
Notifications
You must be signed in to change notification settings - Fork 8
/
proposed_algos.py
426 lines (339 loc) · 15.1 KB
/
proposed_algos.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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
from sklearn.neighbors import LSHForest
from sklearn.neighbors import NearestNeighbors
from competing_algos import calcRev
import numpy as np
import time, math
import random
import pickle
def preprocess(prod, C, p, algo, nEst=10,nCand=40,feasibles = None):
t0 = time.time()
if algo == 'special_case_LSH':
print "\tLSH DB Special init..."
db = LSHForest(n_estimators= nEst, n_candidates=nCand, n_neighbors=C, min_hash_match=3)
elif algo=='general_case_LSH':
print "\tLSH DB General init..."
db = LSHForest(n_estimators= nEst, n_candidates=nCand, n_neighbors=1, min_hash_match=3)
elif algo=="Special_case_BZ":
print "\tBZ DB Special init..."
db = LSHForest(n_estimators= nEst, n_candidates=nCand, n_neighbors=C, min_hash_match=3)
elif algo=='general_case_BZ':
print "\tLSH DB General init..."
db = LSHForest(n_estimators= nEst, n_candidates=nCand, n_neighbors=1, min_hash_match=3)
elif algo=='special_case_exact':
print "\tExact DB Special init..."
db = NearestNeighbors(n_neighbors=C, metric='cosine', algorithm='brute')
else:
print "\tExact DB General init..."
db = NearestNeighbors(n_neighbors=1, metric='cosine', algorithm='brute')
if ((algo == 'special_case_LSH') | (algo=='special_case_exact') | (algo=='special_case_BZ')):
U = np.eye(prod)
normConst = np.sqrt(2+np.max(p)**2)
ptsTemp = np.concatenate((U*np.array(p[1:]),U), axis=1)*1.0/normConst
# print ptsTemp,ptsTemp.shape,1.0/normConst
feasibles = [0 for i in range(ptsTemp.shape[0])] #dummy
else:
normConst = C*np.sqrt(1+np.max(p)**2)
ptsTemp = np.zeros((len(feasibles),2*prod))
for idx,feasible in enumerate(feasibles):
ptsTemp[idx] = np.concatenate((np.array(p[1:])*feasible,feasible))*1.0/normConst
#MIPS to NN transformation of all points
lastCol = np.linalg.norm(ptsTemp, axis=1)**2
lastCol = np.sqrt(1-lastCol)
pts = np.concatenate((ptsTemp, lastCol.reshape((len(feasibles),1))), axis =1)
# for e,fe in enumerate(feasibles):
# print e,np.linalg.norm(p[1:]*feasibles[e]/normConst),np.linalg.norm(pts[e])
# NearestNeighbors(n_estimators= nEst, n_candidates=nCand, n_neighbors=C)
db.fit(pts)
build_time = time.time() - t0
print "\t\tIndex build time: ", build_time
return db, build_time, normConst#,pts
def assortX(prod, C, p, v, eps, algo=None, db=None, normConst=None,feasibles=None):
st = time.time()
L = 0 #L is the lower bound of the search space
U = max(p) #Scalar here
count = 0
queryTimeLog = 0
while (U - L) > eps:
K = (U+L)/2
maxPseudoRev, maxSet,queryTimeLog= get_nn_set(v,p,K,prod,C,db,normConst,algo,feasibles,queryTimeLog)
if (maxPseudoRev/v[0]) >= K:
L = K
# print "going left at count ",count
else:
U = K
# print "going right at count",count
count +=1
maxRev = calcRev(maxSet, p, v,prod)
timeTaken = time.time() - st
return maxRev, maxSet, timeTaken, queryTimeLog
def get_nn_set(v,p,K, prod, C, db, normConst,algo,feasibles=None,queryTimeLog=0):
vTemp = np.concatenate((v[1:], -K*v[1:]))
query = np.concatenate((vTemp, [0])) #appending extra coordinate as recommended by Simple LSH, no normalization being done
#print "query",query
#print "query reshaped", query.reshape(1,-1)
t_before = time.time()
distList, approx_neighbors = db.kneighbors(query.reshape(1,-1),return_distance=True)
queryTimeLog += time.time() - t_before
# print "distList",distList
# print distList<1
# print 1-distList[0]
# print "approx neigh", approx_neighbors
if ((algo == 'special_case_LSH') | (algo=='special_case_exact') | (algo=='special_case_BZ')):
real_neighbours = (distList<1) #consider points only whose dot product with v is strictly positive
real_dist = np.linalg.norm(query)*(1-distList)[0]
real_dist = real_dist * normConst
nn_set = approx_neighbors[0][real_neighbours[0]] + 1 # + 1 is done to identify the product as the indexing would have started from 0
pseudoRev = sum(real_dist[real_neighbours[0]])
else:
nn_set = []
# print 'approx nbhrs', approx_neighbors[0][0]
# print feasibles[0]
for idx in range(len(feasibles[0])):
if feasibles[approx_neighbors[0][0]][idx]==1:
nn_set.append(idx+1)
pseudoRev = np.linalg.norm(query)*(1-distList)*normConst
# pseudoRev = calcRev(nn_set, p, v, prod)
try:
nn_set = list(nn_set.astype(int)) #replace
except:
nn_set = nn_set
return pseudoRev, nn_set,queryTimeLog
# Wrappers
# Assort-Exact-special
def capAst_AssortExactOLD(prod,C,p,v,meta):
maxRev, maxSet, timeTaken, queryTimeLog = assortX(prod, C, p, v,
meta['eps'],
algo = 'special_case_exact',
db=meta['db_exact'],
normConst=meta['normConst'])
print "\t\tAssortExact set:",maxSet
print "\t\tAssortExact cumulative querytime:",queryTimeLog
return maxRev, maxSet, timeTaken
# Assort-LSH-special
def capAst_AssortLSH(prod,C,p,v,meta):
maxRev, maxSet, timeTaken, queryTimeLog = assortX(prod, C, p, v,
meta['eps'],
algo = 'special_case_LSH',
db =meta['db_LSH'],
normConst=meta['normConst'])
print "\t\tAssortLSH set:",maxSet
print "\t\tAssortLSH cumulative querytime:",queryTimeLog
return maxRev, maxSet, timeTaken
# Assort-Exact-general
def genAst_AssortExact(prod,C,p,v,meta):
maxRev, maxSet, timeTaken, queryTimeLog = assortX(prod, C, p, v,
meta['eps'],
algo = 'general_case_exact',
db=meta['db_exact'],
normConst=meta['normConst'],
feasibles=meta['feasibles'])
print "\t\tAssortExact-G set:",maxSet
print "\t\tAssortExact-G cumulative querytime:",queryTimeLog
return maxRev, maxSet, timeTaken
# Assort-LSH-general
def genAst_AssortLSH(prod,C,p,v,meta):
maxRev, maxSet, timeTaken, queryTimeLog = assortX(prod, C, p, v,
meta['eps'],
algo = 'general_case_LSH',
db =meta['db_LSH'],
normConst=meta['normConst'],
feasibles=meta['feasibles'])
print "\t\tAssortLSH-G set:",maxSet
print "\t\tAssortLSH-G cumulative querytime:",queryTimeLog
return maxRev, maxSet, timeTaken
# Assort-Exact-Linear-Scan
def capAst_AssortExact(prod,C,p,v,meta):
def createArray(pminusk,v):
return np.multiply(pminusk,v)
def linearSearch(p,k,v,C,prod):
start = time.time()
maxPseudoRev = 0
maxSet = []
bigArray = createArray(p-K,v)
candidate_product_idxes = np.argsort(bigArray)[prod+1-C:]
maxSet = sorted(candidate_product_idxes[bigArray[candidate_product_idxes] > 0])
maxPseudoRev = sum(bigArray[maxSet])
return maxPseudoRev,maxSet,time.time()-start
st = time.time()
L = 0 #L is the lower bound of the search space
U = max(p) #Scalar here
count = 0
while (U - L) > meta['eps']:
K = (U+L)/2
maxPseudoRev, maxSet,queryTimeLog = linearSearch(p,K,v,C,prod)
print "\t\t\tAssortExact querytime:",queryTimeLog, " for K=",K
if (maxPseudoRev/v[0]) >= K:
L = K
# print "going left at count ",count
else:
U = K
# print "going right at count",count
count +=1
maxRev = calcRev(maxSet, p, v,prod)
timeTaken = time.time() - st
print "\t\tAssortExact Opt Set Size:",len(maxSet)
print "\t\tAssortExact Opt Set:",maxSet
print "\t\tAssortExact Opt Rev:",maxRev
return maxRev, maxSet, timeTaken
#Assort-BZ
def capAst_AssortBZ(prod, C, p, v, meta):
L = 0 # L is the lower bound on the objectiv
st = time.time()
queryTimeLog = 0
count = 0
if meta.get('eps', None) is None:
meta['eps'] = 1e-3
U = max(p) # U is the upper bound on the objective
best_set_revenue = -1
best_set = []
L = meta['eps']
# Inititate NBS parameters and define helper functions
#compstep_prob = meta['default_correct_compstep_probability']
compstep_prob = 1
if 'correct_compstep_probability' in meta.keys():
if meta['correct_compstep_probability'] >= 0.5:
compstep_prob = meta['correct_compstep_probability']
step_width = 1e-1
max_iters = 1000
early_termination_width = 1
belief_fraction = 0.95
# Initialize Uniform Distribution
range_idx = np.arange(L, U, step_width)
range_dist = np.ones_like(range_idx)
range_dist = range_dist / np.sum(range_dist)
range_dist = np.log(range_dist)
def get_pivot(range_dist):
exp_dist = np.exp(range_dist)
alpha = exp_dist.sum() * 0.5
# Finding the median of the distribution requires
# adding together many very small numbers, so it's not
# very stable. In part, we address this by randomly
# approaching the median from below or above.
if random.choice([True, False]):
try:
return range_idx[exp_dist.cumsum() < alpha][-1]
except:
return range_idx[::-1][exp_dist[::-1].cumsum() < alpha][-1]
else:
return range_idx[::-1][exp_dist[::-1].cumsum() < alpha][-1]
def get_belief_interval(range_dist, fraction=belief_fraction):
exp_dist = np.exp(range_dist)
epsilon = 0.5 * (1 - fraction)
epsilon = exp_dist.sum() * epsilon
if (exp_dist[0] < epsilon):
left = range_idx[exp_dist.cumsum() < epsilon][-1]
else:
left = 0
right = range_idx[exp_dist.cumsum() > (exp_dist.sum() - epsilon)][0]
return left, right
for i in range(max_iters):
count += 1
# get Median of Distribution
median = get_pivot(range_dist)
# comparision function
maxPseudoRev, maxSet, queryTimeLog = get_nn_set(v, p, median, prod, C, db = meta['db_BZ'], normConst = meta['normConst'], algo = 'special_case_BZ', feasibles = None, queryTimeLog = 0)
# Compare Set Revenue with bestSet provided, and replace bestSet if more optimal
#current_set_revenue = rcm_calc_revenue(maxSet, p, rcm, num_prods)
current_set_revenue = calcRev(maxSet, p, v, prod)
if current_set_revenue > best_set_revenue:
best_set, best_set_revenue = maxSet, current_set_revenue
if (maxPseudoRev / v[0]) >= median:
range_dist[range_idx >= median] += np.log(compstep_prob)
range_dist[range_idx < median] += np.log(1 - compstep_prob)
else:
range_dist[range_idx <= median] += np.log(compstep_prob)
range_dist[range_idx > median] += np.log(1 - compstep_prob)
# shift all density from lower than best revenue got into upper end
shift_density_total = np.sum(np.exp(range_dist[range_idx < best_set_revenue]))
if (shift_density_total > 0):
range_dist[range_idx < best_set_revenue] = np.log(0)
range_dist[range_idx >= best_set_revenue] += np.log(
shift_density_total / len(range_dist[range_idx >= best_set_revenue]))
# avoid overflows
range_dist -= np.max(range_dist)
belief_start, belief_end = get_belief_interval(range_dist)
if (belief_end - belief_start) <= early_termination_width:
break
timeTaken = time.time()-st
print "\t\tAssortBZ Opt Set Size:",len(best_set)
print "\t\tAssortBZ Opt Set:",best_set
return best_set_revenue, best_set, timeTaken
def genAst_AssortBZ(prod, C, p, v, meta):
L = 0 # L is the lower bound on the objectiv
st = time.time()
queryTimeLog = 0
count = 0
U = max(p) # U is the upper bound on the objective
best_set_revenue = -1
best_set = []
# Inititate NBS parameters and define helper functions
#compstep_prob = meta['default_correct_compstep_probability']
compstep_prob = 0.99
if 'correct_compstep_probability' in meta.keys():
if meta['correct_compstep_probability'] >= 0.5:
compstep_prob = meta['correct_compstep_probability']
step_width = 1e-2
max_iters = 1000
early_termination_width = meta['eps']
belief_fraction = 0.95
# Initialize Uniform Distribution
range_idx = np.arange(L, U, step_width)
range_dist = np.ones_like(range_idx)
range_dist = range_dist / np.sum(range_dist)
range_dist = np.log(range_dist)
def get_pivot(range_dist):
exp_dist = np.exp(range_dist)
alpha = exp_dist.sum() * 0.5
# Finding the median of the distribution requires
# adding together many very small numbers, so it's not
# very stable. In part, we address this by randomly
# approaching the median from below or above.
if random.choice([True, False]):
try:
return range_idx[exp_dist.cumsum() < alpha][-1]
except:
return range_idx[::-1][exp_dist[::-1].cumsum() < alpha][-1]
else:
return range_idx[::-1][exp_dist[::-1].cumsum() < alpha][-1]
def get_belief_interval(range_dist, fraction=belief_fraction):
exp_dist = np.exp(range_dist)
epsilon = 0.5 * (1 - fraction)
epsilon = exp_dist.sum() * epsilon
if (exp_dist[0] < epsilon):
left = range_idx[exp_dist.cumsum() < epsilon][-1]
else:
left = 0
right = range_idx[exp_dist.cumsum() > (exp_dist.sum() - epsilon)][0]
return left, right
for i in range(max_iters):
#logger.info(f"\niteration: {iter_count}")
count += 1
# get Median of Distribution
median = get_pivot(range_dist)
# comparision function
maxPseudoRev, maxSet, queryTimeLog = get_nn_set(v, p, median, prod, C, db = meta['db_BZ'], normConst = meta['normConst'], algo = 'general_case_BZ', feasibles = meta['feasibles'], queryTimeLog = 0)
# Compare Set Revenue with bestSet provided, and replace bestSet if more optimal
current_set_revenue = calcRev(maxSet, p, v, prod)
if current_set_revenue > best_set_revenue:
best_set, best_set_revenue = maxSet, current_set_revenue
if (maxPseudoRev / v[0]) >= median:
range_dist[range_idx >= median] += np.log(compstep_prob)
range_dist[range_idx < median] += np.log(1 - compstep_prob)
else:
range_dist[range_idx <= median] += np.log(compstep_prob)
range_dist[range_idx > median] += np.log(1 - compstep_prob)
# shift all density from lower than best revenue got into upper end
shift_density_total = np.sum(np.exp(range_dist[range_idx < best_set_revenue]))
if (shift_density_total > 0):
range_dist[range_idx < best_set_revenue] = np.log(0)
range_dist[range_idx >= best_set_revenue] += np.log(
shift_density_total / len(range_dist[range_idx >= best_set_revenue]))
# avoid overflows
range_dist -= np.max(range_dist)
belief_start, belief_end = get_belief_interval(range_dist)
if (belief_end - belief_start) <= early_termination_width:
break
timeTaken = time.time()-st
print "\t\tAssortBZ-Z Opt Set Size:",len(best_set)
print "\t\tAssortBZ-Z Opt Set:",best_set
return best_set_revenue, best_set, timeTaken