Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(NegativeSampleGenerator): Prevent duplicate user IDs when getting unique IPs #958

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/Service/NegativeSampleGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
use function str_split;

class NegativeSampleGenerator {
/**
* Get IP vectors exclusively used by one user.
* Includes the user vector in second dimension of the returned array.
*/
private function getUniqueIPsPerUser(Dataset $positives): array {
$map = [];

Expand All @@ -35,7 +39,7 @@ private function getUniqueIPsPerUser(Dataset $positives): array {
$map[$ipVecStr] = [
$uidVecStr,
];
} else {
} elseif (!in_array($uidVecStr, $map[$ipVecStr])) {
$map[$ipVecStr][] = $uidVecStr;
}
}
Expand Down
31 changes: 31 additions & 0 deletions tests/Unit/Service/NegativeSampleGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,37 @@ public function testGenerateMultipleShuffledFromLimitedUnique(): void {
self::assertCount(5, $result);
}

/**
* DataSet can consist of multiple unique entries only. If not handled correctly,
* this will result in an array without any IP. This tests the
* correct handling. See GitHub issue #860 for more.
* @return void
*/
public function testGenerateMultipleShuffledFromUniquesOnly(): void {
$positives = new Unlabeled([
array_merge(self::decToBitArray(1, 16), self::decToBitArray(1, 32)),
array_merge(self::decToBitArray(1, 16), self::decToBitArray(1, 32)),
array_merge(self::decToBitArray(1, 16), self::decToBitArray(1, 32)),

array_merge(self::decToBitArray(2, 16), self::decToBitArray(2, 32)),
array_merge(self::decToBitArray(2, 16), self::decToBitArray(2, 32)),
array_merge(self::decToBitArray(2, 16), self::decToBitArray(2, 32)),
]);

$result = $this->generator->generateShuffledFromPositiveSamples($positives, 2);

self::assertCount(2, $result);
foreach ($result as $sample) {
$ipVec = array_slice($sample, 16, 32);

self::assertTrue(
$ipVec === self::decToBitArray(1, 32) ||
$ipVec === self::decToBitArray(2, 32),
'Sample has an unique IP'
);
}
}

/**
* @return int[]
*/
Expand Down