Skip to content

Commit

Permalink
DBSCAN fix for associative keys and array_merge performance optimizat…
Browse files Browse the repository at this point in the history
…ion (#139)
  • Loading branch information
mvkasatkin authored and akondas committed Oct 18, 2017
1 parent 61d2b7d commit b48b82b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Phpml/Clustering/DBSCAN.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,19 @@ private function expandCluster($samples, &$visited)
{
$cluster = [];

$clusterMerge = [[]];
foreach ($samples as $index => $sample) {
if (!isset($visited[$index])) {
$visited[$index] = true;
$regionSamples = $this->getSamplesInRegion($sample, $samples);
if (count($regionSamples) > $this->minSamples) {
$cluster = array_merge($regionSamples, $cluster);
$clusterMerge[] = $regionSamples;
}
}

$cluster[] = $sample;
$cluster[$index] = $sample;
}
$cluster = \array_merge($cluster, ...$clusterMerge);

return $cluster;
}
Expand Down
13 changes: 13 additions & 0 deletions tests/Phpml/Clustering/DBSCANTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,17 @@ public function testDBSCANSamplesClustering()

$this->assertEquals($clustered, $dbscan->cluster($samples));
}

public function testDBSCANSamplesClusteringAssociative()
{
$samples = ['a' => [1, 1], 'b' => [9, 9], 'c' => [1, 2], 'd' => [9, 8], 'e' => [7, 7], 'f' => [8, 7]];
$clustered = [
['a' => [1, 1], 'c' => [1, 2]],
['b' => [9, 9], 'd' => [9, 8], 'e' => [7, 7], 'f' => [8, 7]],
];

$dbscan = new DBSCAN($epsilon = 3, $minSamples = 2);

$this->assertEquals($clustered, $dbscan->cluster($samples));
}
}

0 comments on commit b48b82b

Please sign in to comment.