Skip to content

Commit

Permalink
Added fromMap function to SparseVector
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jun 25, 2024
1 parent 549a239 commit a5b430d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/SparseVector.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,21 @@ public static function fromDense($value)
return new SparseVector($dimensions, $indices, $values);
}

public static function fromMap($map, $dimensions)
{
$indices = [];
$values = [];
// no need to sort since binary format is not supported
foreach ($map as $i => $v) {
$fv = floatval($v);
if ($fv != 0) {
$indices[] = intval($i);
$values[] = $fv;
}
}
return new SparseVector($dimensions, $indices, $values);
}

public static function fromString($value)
{
$parts = explode('/', $value, 2);
Expand Down
6 changes: 6 additions & 0 deletions tests/SparseVectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ public function testFromDense()
$this->assertEquals([1, 2, 3], $embedding->values());
}

public function testFromMap()
{
$embedding = SparseVector::fromMap([2 => 2, 4 => 3, 0 => 1, 3 => 0], 6);
$this->assertEquals([1, 0, 2, 0, 3, 0], $embedding->toArray());
}

public function testFromString()
{
$embedding = SparseVector::fromString('{1:1,3:2,5:3}/6');
Expand Down

0 comments on commit a5b430d

Please sign in to comment.