|
| 1 | +/* |
| 2 | + * Copyright (c) "Neo4j" |
| 3 | + * Neo4j Sweden AB [http://neo4j.com] |
| 4 | + * |
| 5 | + * This file is part of Neo4j. |
| 6 | + * |
| 7 | + * Neo4j is free software: you can redistribute it and/or modify |
| 8 | + * it under the terms of the GNU General Public License as published by |
| 9 | + * the Free Software Foundation, either version 3 of the License, or |
| 10 | + * (at your option) any later version. |
| 11 | + * |
| 12 | + * This program is distributed in the hope that it will be useful, |
| 13 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 | + * GNU General Public License for more details. |
| 16 | + * |
| 17 | + * You should have received a copy of the GNU General Public License |
| 18 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 19 | + */ |
| 20 | +package org.neo4j.gds.similarity.knn.metrics; |
| 21 | + |
| 22 | +/** |
| 23 | + * We compute the Hamming Distance, |
| 24 | + * (https://en.wikipedia.org/wiki/Hamming_distance) and turn it into |
| 25 | + * a similarity metric by clamping into 0..1 range using a linear |
| 26 | + * transformation. |
| 27 | + */ |
| 28 | +public final class HammingDistance { |
| 29 | + private HammingDistance() {} |
| 30 | + |
| 31 | + public static double longMetric(long left, long right) { |
| 32 | + return normalizeBitCount( |
| 33 | + Long.bitCount(left ^ right) |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * We use unity-based normalization to scale the bit |
| 39 | + * count to the [0-1] range: |
| 40 | + * y = (x_i - min(x)) / (max(x) - min(x)) See |
| 41 | + * https://stats.stackexchange.com/a/70807 for example. |
| 42 | + * In our case, min(x) = 0 since you cannot have a negative |
| 43 | + * bit count, and max(x) = 64 since in Java, a long is |
| 44 | + * 64 bits in size. |
| 45 | + * |
| 46 | + * We then subtract the normalized range from 1.0 to map |
| 47 | + * 1.0 as most similar, and 0.0 as least similar. |
| 48 | + */ |
| 49 | + private static double normalizeBitCount(long bitCount) { |
| 50 | + return 1.0 - (bitCount / 64.0); |
| 51 | + } |
| 52 | +} |
0 commit comments