|
| 1 | +package com.baeldung.lsh; |
| 2 | + |
| 3 | +import info.debatty.java.lsh.LSHMinHash; |
| 4 | +import org.junit.Ignore; |
| 5 | +import org.junit.Test; |
| 6 | + |
| 7 | +import java.util.Arrays; |
| 8 | + |
| 9 | +import static org.assertj.core.api.Assertions.assertThat; |
| 10 | + |
| 11 | + |
| 12 | +public class LocalSensitiveHashingUnitTest { |
| 13 | + |
| 14 | + @Ignore("for simplicity of the example number of input vectors is very low, that's why LSH may yield non deterministic results") |
| 15 | + @Test() |
| 16 | + public void givenNVectors_whenPerformLSH_thenShouldCalculateSameHashForSimilarVectors() { |
| 17 | + //given |
| 18 | + boolean[] vector1 = new boolean[]{true, true, true, true, true}; |
| 19 | + boolean[] vector2 = new boolean[]{false, false, false, true, false}; |
| 20 | + boolean[] vector3 = new boolean[]{false, false, true, true, false}; |
| 21 | + |
| 22 | + int sizeOfVectors = 5; |
| 23 | + int numberOfBuckets = 10; |
| 24 | + int stages = 4; |
| 25 | + |
| 26 | + LSHMinHash lsh = new LSHMinHash(stages, numberOfBuckets, sizeOfVectors); |
| 27 | + |
| 28 | + //when |
| 29 | + int[] firstHash = lsh.hash(vector1); |
| 30 | + int[] secondHash = lsh.hash(vector2); |
| 31 | + int[] thirdHash = lsh.hash(vector3); |
| 32 | + |
| 33 | + System.out.println(Arrays.toString(firstHash)); |
| 34 | + System.out.println(Arrays.toString(secondHash)); |
| 35 | + System.out.println(Arrays.toString(thirdHash)); |
| 36 | + |
| 37 | + //then |
| 38 | + int lastIndexOfResult = stages - 1; |
| 39 | + assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(secondHash[lastIndexOfResult]); |
| 40 | + assertThat(firstHash[lastIndexOfResult]).isNotEqualTo(thirdHash[lastIndexOfResult]); |
| 41 | + assertThat(isCloseOrEqual(secondHash[lastIndexOfResult], thirdHash[lastIndexOfResult], numberOfBuckets)).isTrue(); |
| 42 | + } |
| 43 | + |
| 44 | + private boolean isCloseOrEqual(int secondHash, int thirdHash, int numberOfBuckets) { |
| 45 | + return Math.abs(secondHash - thirdHash) < numberOfBuckets / 2; |
| 46 | + } |
| 47 | +} |
| 48 | + |
0 commit comments