Skip to content

Commit 325f7e2

Browse files
feat: New Tensor operation magnitude, sqrt and cosSimilarity
1 parent 49744a1 commit 325f7e2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/Tensor/Tensor.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -640,6 +640,26 @@ public function sigmoid(): self
640640
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
641641
}
642642

643+
/**
644+
* Calculates the magnitude of the tensor
645+
*
646+
* @return float The magnitude of the tensor.
647+
*/
648+
public function magnitude(): float
649+
{
650+
$mo = self::mo();
651+
652+
return $mo->la()->nrm2($this);
653+
}
654+
655+
656+
public function sqrt(): NDArray
657+
{
658+
$mo = self::mo();
659+
660+
return $mo->la()->sqrt($this);
661+
}
662+
643663
/**
644664
* Return a new Tensor with every element multiplied by a constant.
645665
*
@@ -750,6 +770,20 @@ public function reciprocal(): self
750770
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
751771
}
752772

773+
/**
774+
* Calculates the cosine similarity between this Tensor and another Tensor.
775+
*
776+
* @param Tensor $other The Tensor to calculate the cosine similarity with.
777+
* @return float|int The cosine similarity between this Tensor and the other Tensor.
778+
*/
779+
public function cosSimilarity(Tensor $other): float|int
780+
{
781+
$dotProduct = $this->dot($other);
782+
$magnitude = $this->magnitude();
783+
$otherMagnitude = $other->magnitude();
784+
return $dotProduct / ($magnitude * $otherMagnitude);
785+
}
786+
753787
/**
754788
* Performs `L_p` normalization of inputs over specified dimension.
755789
*

0 commit comments

Comments
 (0)