This repository has been archived by the owner on Jul 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
/
CalculateLSHParameters.m
2045 lines (1736 loc) · 59.5 KB
/
CalculateLSHParameters.m
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function results = CalculateLSHParameters(N, dnnHist, dnnBins, ...
danyHist, danyBins, deltaTarget, r, uHash, uCheck)
% function results = CalculateLSHParameters(N, dnnHist, dnnBins, ...
% danyHist, danyBins, deltaTarget, r, uHash, uCheck)
%
%%%%%%%%%%%%%%%% Calculate Optimal LSH Parameters %%%%%%%%%%%%%%%%%%%%%
% Given the nearest neighbor and any statistics, find the optimal LSH
% parameters. Based on the ArbitraryDistance OPtimization code.
%
% Start with the danyHist, danyBins, dnnHist, dnnBins vectors and calculate
% the expected bin populations.
%
% Input: danyHist, danyBins, dnnHist, dnnBins, N (total number of points)
% D (number of dimensionsm and error tolerance (prob of missing NN).
%
% Output: optimal parameters for LSH. Everything is returned in a big
% structure.
%
% Intermediate Variables (for debugging)
% dScale - Amount to scale axis to make calculations easier.
% dnnPDF, danyPDF (xs)
% Scaled PDF for distances
% projAnyPDF, projNnPDF (xp)
% Scaled PDFs for projected differences
% binAnyProb, binNnProb (wList)
% Prob of hit as a function of w
% Equation numbers refer to second draft of "Optimal Locality-Sensitive
% Hashing" by Malcolm Slaney, Yury Lifshits and Junfeng He, Submitted to
% the Proceeings of the IEEE special issue on Web-Scale Multimedia,
% February 2012.
% Copyright (c) 2010-2012 Yahoo! Inc. See detailed copyright notice at
% the bottom of this file.
debugPlot = 0; % Set to non zero to get debugging plots
%%
%%%%%%%%%%%%%%%%%%% ARGUMENT PARSING %%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin < 5
fprintf('Syntax: results = CalculateLSHParameters(N, ...\n');
fprintf(' dnnHist, dnnBins, danyHist, danyBins, ...\n');
fprintf(' deltaTarget, r, uHash, uCheck);\n');
return;
end
if ~isscalar(N)
error('First argument must be a scalar count.');
end
if ~isvector(dnnHist) || ~isvector(dnnHist) || length(dnnHist) ~= length(dnnBins)
error('dnnHist and dnnBins must be the same length vectors.');
end
if ~isvector(danyHist) || ~isvector(danyHist) || length(danyHist) ~= length(danyBins)
error('danyHist and danyBins must be the same length vectors.');
end
% Set the default parameter values.
if nargin < 6
deltaTarget = 1/exp(1.0);
end
if nargin < 7
r = 1;
end
if nargin < 8
uHash = 1;
end
if nargin < 9
uCheck = 1;
end
%%%%%%%%%%%%%%%% Make sure basic data looks good %%%%%%%%%%%%%%%%%%%%%
if debugPlot
figure(1);
clf;
plot(dnnBins, dnnHist/sum(dnnHist), danyBins, danyHist/sum(danyHist));
legend('Nearest Neighbor', 'Any Neighbor')
title('Histogram of Distances');
xlabel('Distance')
ylabel('Number of Images');
end
% Create the results structure
results = struct('uHash', uHash, 'uCheck', uCheck, 'N', N, ...
'multiprobeR', r, 'dnnBins', dnnBins, 'dnnHist', dnnHist, ...
'danyBins', danyBins, 'danyHist', danyHist, 'delta', deltaTarget);
%%
%%%%%%%%%%%%%%%%%%% SCALING %%%%%%%%%%%%%%%%%%%%%%%%%%
% Figure out scaling before computing PDFs
% Want to make sure that max dany isn't too big or small so we can invert
% the PDF.
targetMean = 2;
danyMean = sum(danyHist.*danyBins)/sum(danyHist);
dScale = targetMean/danyMean;
fprintf('Scaling all distances by %g for easier probability calcs.\n', ...
dScale);
%%
% Create new scales and interpolate everything
% Create the distance PDFs with the new scale.
% Scale bin sizes so we have enough resolution for calculations
% xs is the sampling grid for the distance profiles (positive only)
nnBinWidth = min(dnnBins(2:end)-dnnBins(1:end-1))*dScale/2;
xs = 0:nnBinWidth:max(danyBins)*dScale*2;
dnnPDF = max(0, interp1(dnnBins*dScale, dnnHist, xs, 'linear', 0));
danyPDF = max(0, interp1(danyBins*dScale, danyHist, xs, 'linear', 0));
results.xs = xs;
results.dnnPDF = dnnPDF;
results.danyPDF = danyPDF;
results.dScale = dScale;
if debugPlot
figure(2);
clf
plot(xs/dScale, dnnPDF, xs/dScale, danyPDF);
legend('Nearest Neighbor', 'Any Neighbor')
title('Distance Distributions');
xlabel('Scaled Distance - mean(d_{any}) = 2')
ylabel('PDF of Distance');
end
%%
%%%%%%%%%%%%%%%%%%% CREATE AXIS FOR RESULTS %%%%%%%%%%%%%%%%%%%%%%%%%%
% Be careful to make sure that new distributions fit into bins, no
% truncation.
expansionFactor = 1; % Amount to increase over distance histograms
maxBin = expansionFactor*max(xs);
% Don't let nnBinWidth get too small because pdfinv creates a square matrix
% xp is the sampling grid for the projection data.
nnBinWidth = max(maxBin/1000.0, nnBinWidth);
xp = -maxBin:nnBinWidth:maxBin;
xp(abs(xp)<1e-9) = 1e-9;
results.xp = xp;
%%
%%%%%%%%%%%%%%%%%%% COMPUTE PROJECTION PDFs %%%%%%%%%%%%%%%%%%%%%%%%%%
% Create the Gaussian N(0,1) distribution we'll use for
% the LSH projection;
lshGaussian = simplepdf(xp, 0, 1, 'gaussian');
% Now multiply the projection PDF with the Gaussian PDF to get the LSH
% projection.
% Don't flip the order.. second term gets inverted and perhaps the
% Gaussian always has enough energy in the tails that we get the
% wrong answer at zero.
projAnyPDF = pdfmult(xp, xs, lshGaussian, danyPDF, xp);
projNnPDF = pdfmult(xp, xs, lshGaussian, dnnPDF, xp);
if any(isnan(projNnPDF))
nnMean = sum(xs .* dnnPDF) / sum(dnnPDF);
projNnPDF = NormalizePDF(simplepdf(xp, 0, nnMean, 'gaussian'), xp)';
end
results.projAnyPDF = projAnyPDF;
results.projNnPDF = projNnPDF;
if debugPlot
figure(3);
subplot(2,1,1);
vScale = max(dnnPDF*dScale)/max(projNnPDF*dScale);
plot(xs/dScale, dnnPDF*dScale/vScale, xp/dScale, projNnPDF*dScale);
legend('Empirical dnn Distrution', ...
'Calculated NN LSH Projection', ...
'Location','NorthWest');
title('NN LSH Projection');
xlabel('Distance');
subplot(2,1,2);
vScale = max(danyPDF*dScale)/max(projAnyPDF*dScale);
plot(xs/dScale, danyPDF*dScale/vScale, xp/dScale, projAnyPDF*dScale);
legend('Empirical dany Distribution', ...
'Calculated LSH Projection', ...
'Location','NorthWest');
title('Any Projection Histogram');
xlabel('Distance')
end
%%
%%%%%%%%%%%%%%%%%%% BUCKET ESTIMATES %%%%%%%%%%%%%%%%%%%%%%%%%%
% Now compute number of hits vs bin size.
% Create the matrix that convolves the projection data with a triangular
% window to represent the quantization interval.
% wMaxSize = 256*dnnBins(end);
minW = .001;
maxW = 100.0;
numWs = 500;
deltaW = exp(log(maxW/minW)/(numWs-1));
wList = minW * deltaW .^(0:numWs-1);
deltaMatrix = zeros(length(xp), length(wList));
for i=1:length(wList)
deltaMatrix(:,i) = max(0, 1-abs(xp')/wList(i));
end
% Now compute how many hits there are in the query's bucket, as a function
% of the bin width.
xpBinWidth = xp(3)-xp(2); % For example
binAnyProb = projAnyPDF' * deltaMatrix * xpBinWidth;
binNnProb = projNnPDF' * deltaMatrix * xpBinWidth;
% Now do the same thing for the multiprobe buckets
delta2Matrix = zeros(length(xp), length(wList));
for i=1:length(wList)
% delta2Matrix(:,i) = max(0, 1-abs(xp'-wList(i))/wList(i));
delta2Matrix(:,i) = max(0, min(1, (1.5 + -2*abs(xp'/wList(i)-.75))));
end
binAnyProb2 = projAnyPDF' * delta2Matrix * xpBinWidth;
binNnProb2 = projNnPDF' * delta2Matrix * xpBinWidth;
if 0 % Is this still necessary?
binAnyProb = min(binAnyProb, 0.9999);
binAnyProb = max(binAnyProb, 0.0001);
binNnProb = min(binNnProb, 0.9999);
binNnProb = max(binNnProb, 0.0001);
binAnyProb2 = min(binAnyProb2, 0.9999);
binAnyProb2 = max(binAnyProb2, 0.0001);
binNnProb2 = min(binNnProb2, 0.9999);
binNnProb2 = max(binNnProb2, 0.0001);
end
if debugPlot
figure(4)
clf;
semilogx(wList/dScale, [binNnProb' binAnyProb' binNnProb2' binAnyProb2']);
legend('p_{nn}', 'p_{any}','q_{nn}', 'q_{any}','Location','NorthWest');
title('LSH Bucket Estimate')
ylabel('Collision Probabilities')
xlabel('Bin Width (w)')
axis([1e-2/dScale 4e1/dScale 0 1]);
end
results.binAnyProb = binAnyProb;
results.binNnProb = binNnProb;
results.binAnyProb2 = binAnyProb2;
results.binNnProb2 = binNnProb2;
results.wList = wList;
%%
%%%%%%%%%%%%%%%% SIMPLE PARAMETER ESTIMATES %%%%%%%%%%%%%%%%%%%%%%%
% Now find best LSH parameters using Simple calcs
temp1 = (-log(binAnyProb)/log(N)).^r + ...
uHash/uCheck * (binAnyProb2./binAnyProb).^r;
costRatioForMultiProbe = (factorial(r))*(binNnProb./binNnProb2).^r .* ...
temp1;
% results.costRatioForMultiProbe = costRatioForMultiProbe;
fixedRatio = costRatioForMultiProbe .* N.^(log(binNnProb)./log(binAnyProb));
% fixedRatio(isinf(fixedRatio)) = nan;
results.wSimpleCost = fixedRatio;
[simpleMax, simpleBin] = min(fixedRatio);
simpleW = wList(simpleBin)/dScale;
simpleK = floor(-log(N)/log(binAnyProb(simpleBin)));
simpleL = -log(deltaTarget)/ ...
( simpleK^r/factorial(r) * (binNnProb(simpleBin)^(simpleK-r)) * ...
(binAnyProb2(simpleBin)^r) );
simpleL = ceil(simpleL);
% Equations (20) and (21) for cost factors
Ch = uHash*(-log(deltaTarget)) * ...
factorial(r) * (binNnProb(simpleBin)/binNnProb2(simpleBin))^r;
Cc = uCheck * (-log(deltaTarget))*N* ...
((binNnProb(simpleBin)./binNnProb2(simpleBin)))^r * ...
(binAnyProb2(simpleBin)/binAnyProb(simpleBin))^r;
simpleCost = Ch/( (simpleK^r) * (binNnProb(simpleBin)^simpleK))+ ...
Cc * (binAnyProb(simpleBin)/binNnProb(simpleBin))^simpleK;
fprintf('Simple Approximation:\n');
fprintf('\tFor %d points of data use: ', N);
fprintf('w=%g and get %g hits per bin and %g nn.\n', ...
simpleW, binAnyProb(simpleBin), ...
binNnProb(simpleBin));
fprintf('\t\tK=%g L=%g cost is %g\n', ...
simpleK, simpleL, simpleCost);
results.simpleW = simpleW;
results.simpleK = simpleK;
results.simpleL = simpleL;
results.simpleBin = simpleBin;
results.simpleCost = simpleCost;
% Now plot the statistics for L=1 for simple parameters.
% For L=1
desiredSimpleK = round(simpleK);
desiredSimpleL = round(simpleL);
nnHitProbL1 = binNnProb(simpleBin)^desiredSimpleK;
anyHitProbL1 = binAnyProb(simpleBin)^desiredSimpleK;
nnHitProb = 1 - (1-nnHitProbL1)^desiredSimpleL;
anyHitProb = 1 - (1-anyHitProbL1)^desiredSimpleL;
fprintf('Expected statistics: for simple approximation\n');
fprintf('\tAssuming K=%d, L=%d, hammingR=%d\n', desiredSimpleK, desiredSimpleL, r);
fprintf('\tProbability of finding NN for L=1: %g\n', nnHitProbL1);
fprintf('\tProbability of finding ANY for L=1: %g\n', anyHitProbL1);
fprintf('\tProbability of finding NN for L=%d: %g\n', desiredSimpleL, nnHitProb);
fprintf('\tProbability of finding ANY for L=%d: %g\n', desiredSimpleL, anyHitProb);
fprintf('\tExpected number of hits per query: %g\n', anyHitProb*N);
%%
%%%%%%%%%%%%%%%%%%% EXACT PARAMETER ESTIMATION %%%%%%%%%%%%%%%%%%%%%%
% Now do it with the full optimal calculations
% Eq. 30 for all values of w
wAlpha = log((binNnProb-binAnyProb)./(1-binNnProb)) + ...
r * log(binAnyProb2./binAnyProb) + log(uCheck/uHash) - log(factorial(r));
% Eq. 32 for all values of w. Added rprime definition to make things
% easier.
rprime = r ./ (-log(binAnyProb));
wBestK = (log(N)+wAlpha)./(-log(binAnyProb)) + ...
rprime.*log((log(N)+wAlpha)./(-log(binAnyProb)));
wBestK(imag(wBestK) ~= 0.0 | wBestK < 1) = 1; % Set bad values to at least 1
% Now we want to find the total cost for all values of w. We will argmin
% this for find the best w (This is the inside of Eq. 39. We first compute
% the inside of x^(log/log)
% Equations (20) and (21) for cost factors.
Ch = uHash * (-log(deltaTarget)) * ...
factorial(r) * (binNnProb./ binNnProb2).^r;
Cc = uCheck * (-log(deltaTarget))*N*((binNnProb./binNnProb2)).^r .* ...
(binAnyProb2./binAnyProb).^r;
wFullCost = Ch /( (wBestK.^r) .* (binNnProb.^wBestK)) + ...
Cc .* (binAnyProb./binNnProb).^wBestK;
results.wExpExactCost = wFullCost;
% Now compute the integer values of k and l.
% Don't let r get bigger than k (vs. W), which can happen for very small w.
kVsW = floor(wBestK);
% We compute L via Equation (17)
lVsW = ceil(-log(deltaTarget)./ ...
( choose(kVsW, min(r, kVsW)) .* (binNnProb.^(max(1,wBestK-r))) .* ...
(binNnProb2.^r)));
[optimalMin, optimalBin] = min(wFullCost);
optimalW = wList(optimalBin)/dScale;
optimalK = kVsW(optimalBin);
optimalL = lVsW(optimalBin);
results.exactW = optimalW;
results.exactK = optimalK;
results.exactL = optimalL;
results.exactBin = optimalBin;
results.exactCost = wFullCost(optimalBin);
results.wExactK = wBestK;
results.wExactL = lVsW;
results.wExactCost = wFullCost;
% Now figure out the best possible estimate of the total number of
% candidates we will check. Sum over all distances < r.
probSum = 0;
for ri = 0:r
candidatesPerBucket = choose(kVsW, min(ri, kVsW)) .* ...
results.binAnyProb.^max(0,kVsW-ri) .* ...
results.binAnyProb2.^ri;
probSum = probSum + candidatesPerBucket;
end
results.wCandidateCount = N * (1 - (1-probSum).^lVsW);
results.wCandidateCount2 = N*probSum.*lVsW;
results.exactCandidateCount = results.wCandidateCount(optimalBin);
fprintf('Exact Optimization:\n');
fprintf('\tFor %d points of data use: ', N);
fprintf('w=%g and get %g hits per bin and %g nn.\n', ...
optimalW, binAnyProb(optimalBin), ...
binNnProb(optimalBin));
fprintf('\t\tK=%g L=%g cost is %g\n', ...
optimalK, optimalL, wFullCost(optimalBin));
% And print the statistics for L=1 for simple parameters.
desiredOptimalK = round(optimalK);
desiredOptimalL = round(optimalL);
% nnHitProbL1 = binNnProb(optimalBin)^desiredOptimalK;
% anyHitProbL1 = binAnyProb(optimalBin)^desiredOptimalK;
% From the definition of p_nn in Eq. (46)
nnHitProbL1 = choose(desiredOptimalK, r) * ...
binNnProb(optimalBin)^(desiredOptimalK-r)*...
binNnProb2(optimalBin)^(r);
anyHitProbL1 = choose(desiredOptimalK, r) * ...
binAnyProb(optimalBin)^(desiredOptimalK-r)*...
binAnyProb2(optimalBin)^(r);
nnHitProb = 1 - (1-nnHitProbL1)^desiredOptimalL;
anyHitProb = 1 - (1-anyHitProbL1)^desiredOptimalL;
%%
%%%%%%%%%%%%%%%%%%% Brute Force Calculation %%%%%%%%%%%%%%%%%%%%%%%%%%
if 1
maxK = optimalK + 10;
Ts = zeros(length(binNnProb), maxK);
for k=1:maxK
% Equation 19 for T_s(w)
cPnnQnn = choose(k, min(r, k))*binNnProb.^(k-r).*binNnProb2.^r;
cPanyQany = choose(k, min(r, k))*binAnyProb.^(k-r).*binAnyProb2.^r;
TsByW = uHash * (-log(deltaTarget)) ./ cPnnQnn + ...
uCheck * N * (-log(deltaTarget)) * cPanyQany ./ cPnnQnn;
Ts(:,k) = TsByW;
end
% http://stackoverflow.com/questions/2635120/how-can-i-find-the-maximum-or-minimum-of-a-multi-dimensional-matrix-in-matlab
[min_Ts, min_Ts_position] = min(Ts(:));
% transform the index in the 1D view to 2 indices, given the size of Ts
[minBruteBin,minBruteK] = ind2sub(size(Ts), min_Ts_position);
results.Ts = Ts;
results.bruteBin = minBruteBin;
results.bruteCost = min_Ts;
results.bruteK = minBruteK;
results.bruteW = wList(minBruteBin)/dScale;
results.bruteCandidates = ...
N*choose(results.bruteK, min(r, results.bruteK)) * ...
(binAnyProb(minBruteBin)^(max(1,results.bruteK-r))) * ...
(binAnyProb2(minBruteBin).^r);
results.bruteL = ceil(-log(deltaTarget) / ...
( choose(results.bruteK, min(r, results.bruteK)) * ...
(binNnProb(minBruteBin)^(max(1,results.bruteK-r))) * ...
(binNnProb2(minBruteBin).^r)));
results.bruteCost = results.bruteL*uHash + results.bruteCandidates*uCheck;
if debugPlot
figure(6);
clf
TsDetail = min(results.Ts, 10*min_Ts);
imagesc(log10(results.wList/results.dScale), ...
1:size(TsDetail, 2), ...
log10(TsDetail')); axis ij
xlabel('Log10 Bin Size (w)'); ylabel('Number of Projections (k)');
title('Log10(T_s) by Brute Force');
colorbar;
hold on;
plot(log10(results.bruteW), results.bruteK, 'wo');
plot(log10(results.exactW), results.exactK,'w*');
plot(log10(results.simpleW), results.simpleK, 'wx');
hold off;
end
end
%%
%%%%%%%%%%%%%%%%%%% Summarize the results %%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('Expected statistics for optimal solution:\n');
fprintf('\tAssuming K=%d, L=%d, hammingR=%d\n', desiredOptimalK, ...
desiredOptimalL, r);
fprintf('\tp_nn(w) is %g\n', binNnProb(optimalBin));
fprintf('\tp_any(w) is %g\n', binAnyProb(optimalBin));
fprintf('\tProbability of finding NN for L=1: %g\n', nnHitProbL1);
fprintf('\tProbability of finding ANY for L=1: %g\n', ...
anyHitProbL1);
fprintf('\tProbability of finding NN for L=%d: %g\n', ...
desiredOptimalL, nnHitProb);
fprintf('\tProbability of finding ANY for L=%d: %g\n', ...
desiredOptimalL, anyHitProb);
fprintf('\tExpected number of hits per query: %g\n', ...
results.wCandidateCount(optimalBin));
%%
if debugPlot
figure(5);
clf
subplot(4,1,1);
semilogx(wList/dScale, [binNnProb' binAnyProb']);
legend('Pnn', 'Pany','Location','NorthWest');
title('LSH Bucket Estimate')
ylabel('Collision Probabilities')
xlabel('Bin Width (w)')
% axis([1e-2/dScale 2e1/dScale 0 1]);
subplot(4,1,2);
semilogx(wList/dScale, [log(binNnProb') log(binAnyProb')]);
title('LSH Bucket Estimate (Log Scale)')
xlabel('Bin Width (w)');
ylabel('Log(Collision Probabilities)');
legend('Log(Pnn)', 'Log(Pany)', 'Location','NorthWest');
subplot(4,1,3);
semilogx(wList/dScale, wFullCost);
ylabel('Full Cost')
xlabel('Bin Width (w)');
% axis([1e-2/dScale 2e1/dScale 0 5]);
title('Optimal Cost vs. Bin Width');
hold on
semilogx(wList(optimalBin)/dScale, optimalMin, 'rx');
hold off
subplot(4,1,4);
semilogx(wList/dScale, fixedRatio);
ylabel('Cost Exponent')
xlabel('Bin Width (w)');
% axis([1e-2/dScale 2e1/dScale 0 5]);
title('Simplified Cost vs. Bin Width');
hold on
semilogx(wList(simpleBin)/dScale, simpleMax, 'rx');
hold off
end
% save Test6DGaussian N D deltaTarget binNnProb binAnyProb uCheck uHash wList dScale
%%
% Using Equation 17 of Casey's TASLP paper, calculate the underlying
% dimensionality.
%
% Want to compute
% S = sum x_i where x_i is distance^2
% L = sum log(x_i) where x_i is distance^2
% N is the number of points.
% Define
% Y(x) = log(x) - psi(x)
%
% Want to compute
% d = 2 Y^-1(log(S/N) - L/N))
x = danyBins.^2;
S = sum(x .* danyHist);
goodI = danyHist > 0;
L = sum(log(x(goodI)) .* danyHist(goodI));
% N = sum(danyHist);
wantedY = log(S/N)- L/N;
di = 1:.01:200;
Yi = log(di)-psi(di);
% plot(di,Yi); % Check the Yi relationship
[ignore,i] = min(abs(wantedY-Yi));
globalD = 2*di(i);
results.globalD = globalD;
%%
% Equation 36 of Casey's paper does the same calculation using the dnn
% information. We want to calculate
% d^2 = 4 pi^2/6 mean(x_i)^2 / var(x_i)
% again where x_i is the distance squared.
x = dnnBins.^2;
S = sum(x .* dnnHist);
m = S/sum(dnnHist);
v = sum((x - m).^2 .* dnnHist)/(sum(dnnHist)-1);
localD = sqrt(4*pi^2/6*m^2/v);
results.localD = localD;
% Copyright (c) 2011, Yahoo! Inc.
% All rights reserved.
%
% Redistribution and use of this software in source and binary forms,
% with or without modification, are permitted provided that the following
% conditions are met:
%
% * Redistributions of source code must retain the above
% copyright notice, this list of conditions and the
% following disclaimer.
%
% * Redistributions in binary form must reproduce the above
% copyright notice, this list of conditions and the
% following disclaimer in the documentation and/or other
% materials provided with the distribution.
%
% * Neither the name of Yahoo! Inc. nor the names of its
% contributors may be used to endorse or promote products
% derived from this software without specific prior
% written permission of Yahoo! Inc.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
% IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
% TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
% PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
% OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
% SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
% LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
% THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function c = choose(n, k)
% function c = choose(n, k)
% Works for vectors of n
c = factorial(n) ./ (factorial(k) .* factorial(max(0,n-k)));
%%
function normed = NormalizePDF(y,x)
x = [2*x(1)-x(2) x(:)' 2*x(end)-x(end-1)];
dx = (x(3:end)-x(1:end-2))/2;
area = dx .* y;
normed = y/sum(area);
if 0
t1 = 0:.1:pi;
y1 = sin(t1);
t2 = 0:.24:pi;
y2 = sin(t2);
n1 = NormalizePDF(y1, t1);
n2 = NormalizePDF(y2, t2);
clf; hold on
plot(t1, n1);
plot(t2, n2);
hold off
end
%%%%%%%%%%%%%%%%%%% JLAB Routines %%%%%%%%%%%%%%%%%%%%%%%%%
% The following routines were written by J. M. Lilly
% as part of the Matlab jlab package. The entire package can be found at
% http://www.jmlilly.net/jmlsoft.html
% I am grateful for permission to include Dr. Lilly's PDF code in this
% package.
%%%%%%%%%%%%%%%%%%% JLAB Routines %%%%%%%%%%%%%%%%%%%%%%%%%
%JLAB_LICENSE License statement and permissions for JLAB package.
%
% Copyright (C) 1993--2011 J.M. Lilly
% _______________________________________________________________________
%
% Citation
%
% If you use this software in research resulting in a scientific
% publication, the software should be acknowledged and cited as
%
% Lilly, J. M. (2011), JLAB: Matlab freeware for data analysis,
% Version 0.92, http://www.jmlilly.net/software.html.
% _______________________________________________________________________
%
% License
%
% JLAB is distributed under the
%
% "Creative Commons Attribution Noncommercial-Share Alike License"
%
% Version 3.0, available at
%
% http://creativecommons.org/licenses/by-nc-sa/3.0/us/
%
% You are free:
%
% To Share -- To copy, distribute and transmit the work
%
% To Remix -- To adapt the work
%
% Under the following conditions:
%
% Attribution -- You must attribute the work in the manner specified
% by the author or licensor (but not in any way that suggests that
% they endorse you or your use of the work).
%
% Noncommercial -- You may not use this work for commercial purposes.
%
% Share Alike -- If you alter, transform, or build upon this work,
% you may distribute the resulting work only under the same or
% similar license to this one.
%
% See the above link for the full text of the license.
% _______________________________________________________________________
%
% Disclaimer
%
% This software is provided 'as-is', without any express or implied
% warranty. In no event will the author be held liable for any damages
% arising from the use of this software.
% _______________________________________________________________________
%
% This is part of JLAB --- type 'help jlab' for more information
% (C) 1993--2011 J.M. Lilly --- type 'help jlab_license' for details
function[f]=simplepdf(x,mu,sig,flag)
%SIMPLEPDF Gaussian, uniform, Cauchy, and exponential pdfs.
%
% F=SIMPLEPDF(X,MU,SIG,'gaussian') computes a Gaussian pdf with mean
% MU and standard deviation SIG.
%
% F=SIMPLEPDF(X,MU,SIG,'boxcar') computes a uniform pdf with mean MU
% and standard deviation SIG.
%
% F=SIMPLEPDF(X,XO,wAlpha,'cauchy') computes a Cauchy pdf with location
% parameter XO and scale parameter wAlpha.
%
% F=SIMPLEPDF(X,BETA,'exponential') computes an exponential pdf with
% scale parameter, hence mean and standard deviation, equal to BETA.
%
% 'simplepdf --f' generates a sample figure
%
% Usage: f=simplepdf(x,mu,sig,'gaussian');
% f=simplepdf(x,mu,sig,'boxcar');
% f=simplepdf(x,xo,wAlpha,'cauchy');
% f=simplepdf(x,beta,'exponential');
% __________________________________________________________________
% This is part of JLAB --- type 'help jlab' for more information
% (C) 2001--2008 J.M. Lilly --- type 'help jlab_license' for details
warning('off','MATLAB:divideByZero')
if strcmp(x,'--f')
simplepdf_fig;
return
end
dx=x(2)-x(1);
if nargin==3
flag=sig;
end
if nargin<3&&strcmp(flag,'exponential')||nargin<4&&~strcmp(flag,'exponential')
error('Not enough input arguments.')
end
if strcmp(flag,'gaussian')
f=exp(-(x-mu).^2./2./sig.^2)./sig./sqrt(2*pi);
elseif strcmp(flag,'boxcar')
f=0*x;
ia=min(find(x-mu>-3.4641*sig/2))-1;
ib=min(find(x-mu>3.4641*sig/2));
f(ia:ib)=1;
f=f./vsum(f*dx,1);
elseif strcmp(flag,'cauchy')
wAlpha=sig;
f=frac(wAlpha./pi,(x-mu).^2 + wAlpha.^2);
elseif strcmp(flag,'exponential')
f=frac(1,mu).*exp(-abs(x)./mu);
end
warning('on','MATLAB:divideByZero')
function[]=simplepdf_fig
x=(-100:.1:100)';
mu=25;
sig=10;
f=simplepdf(x,mu,sig,'gaussian');
%[mu2,sig2]=pdfprops(x,f);
figure,plot(x,f),vlines(mu,'r')
%a=conflimit(x,f,95);
%vlines(mu+a,'g'),vlines(mu-a,'g')
title('Gaussian with mean 25 and standard deviation 10')
function[fz]=pdfmult(xi,yi,fx,fy,zi)
%PDFMULT Probability distribution from multiplying two random variables.
%
% FZ=PDFMULT(XI,YI,FX,FY,ZI), given two probability distribution
% functions FX and FY defined over XI and YI, returns the pdf FZ
% corresponding to Z=X*Y over values ZI.
%
% PDFMULT uses PDFDIVIDE.
%
% Usage: yn=pdfmult(xi,yi,fx,fy,zi);
%
% 'pdfmult --f' generates a sample figure.
% __________________________________________________________________
% This is part of JLAB --- type 'help jlab' for more information
% (C) 2001--2009 J.M. Lilly --- type 'help jlab_license' for details
if strcmp(xi,'--f')
pdfmult_fig;
return
end
vcolon(xi,yi,fx,fy,zi);
fyi=jinterp(yi,fy,zi);
fxi=jinterp(xi,fx,zi);
vswap(fyi,nan,0);
vswap(fxi,nan,0);
fyinv=pdfinv(zi,fyi);
fz=pdfdivide(zi,zi,fxi,fyinv,zi);
[mu,sigma]=pdfprops(zi,fz);
function[]=pdfmult_fig
dx=0.1;
dy=0.05;
dz=0.025;
s1=1;
s2=2;
xi=(-10:dx:10)';
yi=(-10:dy:10)';
zi=(-10:dz:10)';
fx=simplepdf(xi,0,s1,'gaussian');
fy=simplepdf(yi,0,s2,'gaussian');
fz0=s1.*s2./pi./(s2.^2.*xi.^2+s1.^2);
fz0=fz0./vsum(fz0*dx,1);
fz=pdfmult(xi,yi,fx,fy,zi);
figure,plot(zi,fz),hold on,plot(xi,fx)
plot(yi,fy)
linestyle default
title('RV with green pdf multiplied by RV with red pdf equals RV with blue pdf')
x1=randn(100000,1)*s1;
y1=randn(100000,1)*s2;
[fz1,n]=hist(x1.*y1,(-10:.1:10));
plot(n,fz1/10000,'.')
text(4,0.4,'Green and red are Gaussian')
text(4,0.35,'Blue is disribution of product')
text(4,0.30,'Dots are from a random trial')
axis([-10 10 0 0.45])
function[varargout]=vcolon(varargin)
%VCOLON Condenses its arguments, like X(:).
%
% [Y1,Y2, ... YN]=VCOLON(X1,X2, ... XN) is equivalent to
%
% Y1=X1(:); Y2=X2(:); ... YN=XN(:);
%
% VCOLON(X1,X2,...XN) with no output arguments overwrites the
% original input variables.
% __________________________________________________________________
% This is part of JLAB --- type 'help jlab' for more information
% (C) 2000, 2004 J.M. Lilly --- type 'help jlab_license' for details
if strcmp(varargin{1}, '--t')
vcolon_test,return
end
for i=1:nargin
x=varargin{i};
varargout{i}=x(:);
end
eval(to_overwrite(nargin));
function[]=vcolon_test
x=[1 3; 2 4];
y=x;
vcolon(x,y);
reporttest('VCOLON ', all(x==(1:4)'&y==(1:4)'))
function[]=reporttest(str,bool)
%REPORTTEST Reports the result of an m-file function auto-test.
%
% Called by JLAB_RUNTESTS.
% _________________________________________________________________
% This is part of JLAB --- type 'help jlab' for more information
% (C) 2003--2009 J.M. Lilly --- type 'help jlab_license' for details
global BOOL_JLAB_RUNTEST
global FUNCTION_NUMBER
global FUNCTION_NUMBER_ARRAY
FUNCTION_NUMBER_ARRAY=[FUNCTION_NUMBER_ARRAY;FUNCTION_NUMBER];
if bool
disp([str ' test: passed'])
BOOL_JLAB_RUNTEST=[BOOL_JLAB_RUNTEST;1];
else
disp([str ' test: FAILED'])
BOOL_JLAB_RUNTEST=[BOOL_JLAB_RUNTEST;0];
end
function[str]=to_overwrite(N)
%TO_OVERWRITE Returns a string to overwrite original arguments.
%
% STR=TO_OVERWRITE(N), when called from within an m-file which has
% VARARGIN for the input variable, returns a string which upon
% EVAL(STR) will cause the first N input variables in the caller
% workspace with the values contained in the first N elements of
% VARARGOUT.
%
% See also TO_GRAB_FROM_CALLER.
%
% Usage: eval(to_overwrite(N))
% __________________________________________________________________
% This is part of JLAB --- type 'help jlab' for more information
% (C) 2001--2006 J.M. Lilly --- type 'help jlab_license' for details
str{1}= 'if nargout==0';
str{end+1}= ' global ZZoutput';
str{end+1}= ' evalin(''caller'',[''global ZZoutput''])';
str{end+1}=[' for i=1:' int2str(N)];
str{end+1}= ' if ~isempty(inputname(i))';
str{end+1}= ' ZZoutput=varargout{i};';
str{end+1}= ' assignin(''caller'',inputname(i), ZZoutput)';
str{end+1}= ' end';
str{end+1}= ' end';
str{end+1}=' evalin(''caller'',[''clear ZZoutput''])';
str{end+1}='end';
str=strs2row(str);
function[row]=strs2row(x)
%STRS2ROW Converts a cell array of strings into a row array
M=length(x);
for i=1:M
n(i)=length(x{i});
end
N=max(n);
row=[];
for i=1:M
row=[row,char(10),x{i}];
end
function[yi]=jinterp(x,y,xi,str)
%JINTERP Matrix-matrix 1-D interpolation.
%
% YI=JINTERP(X,Y,XI), returns the linear interpolation of Y onto XI
% based on the functional relationship Y(X).
%
% Unlike INTERP1, JINTERP allows X,Y, and XI to be either vectors or
% matrices. If more than one argument is a matrix, those matrices must
% be of the same size. YI is a matrix if any input argument is a
% matrix. All vectors should be column vectors and all matrices should
% have data in columns.
%
% Also, only data points of XI in between the maximum and minimum
% values of X are interpolated.
%
% This useful, for example, in interpolating section data with
% nonuniform pressure levels onto standard levels.
%
% See also INTERP1.
% __________________________________________________________________
% This is part of JLAB --- type 'help jlab' for more information
% (C) 2000--2008 J.M. Lilly --- type 'help jlab_license' for details
if nargin~=4
str='linear';
end
%convert row vectors to column vectors
if size(x,1)==1
x=conj(x');
end
if size(y,1)==1
y=conj(y');
end
if size(xi,1)==1
xi=conj(xi');
end
%ensure sizes are compatible
Lx=size(x,2);
Ly=size(y,2);
Lxi=size(xi,2);
maxL=max([Lx Ly Lxi]);
bool=(Lx==1|Lx==maxL)&(Ly==1|Ly==maxL)&(Lxi==1|Lxi==maxL);
if ~bool,
error('Arguments are not of compatible size')
end
%convert vectors to matrices
if Lx==1
x=x*ones(1,maxL);
end
if Ly==1
y=y*ones(1,maxL);
end
if Lxi==1
xi=xi*ones(1,maxL);
end
yi=nan*ones(size(xi,1),maxL);
%check x for monotonicity
mdx=min(min(diff(x)));
if mdx<=0
disp('Ensuring monotonicity of X by adding noise and sorting.')
mx=min(min(x));
x=x+randn(size(x))/1000/1000;
x=sort(x,1);
end
for i=1:size(x,2)
colmin=min(x(isfinite(x(:,i)),i));
colmax=max(x(isfinite(x(:,i)),i));
% a=min(find(xi(:,i)>=colmin));
% b=max(find(xi(:,i)<=colmax));
index=find(xi(:,i)>=colmin&xi(:,i)<=colmax&isfinite(xi(:,i)));
if ~isempty(index)>=0,
yi(index,i)=interp1(x(:,i),y(:,i),xi(index,i),str);
end
end
function[b]=allall(x)
%ALLALL(X)=ALL(X(:))
% _________________________________________________________________
% This is part of JLAB --- type 'help jlab' for more information
% (C) 2004 J.M. Lilly --- type 'help jlab_license' for details
b=all(x(:));
function[fz]=pdfinv(yi,fy)
%PDFINV Probability distribution of the inverse of a random variable.
%
% YN=PDFMULT(YI,FY) given a probability distribution functions FY
% defined over YI, returns the pdf of the inverse random variable 1/Y.
%