From 37782eba98ea62f245b5b6a6fd4674191b884263 Mon Sep 17 00:00:00 2001 From: Arkadiusz Kondas Date: Thu, 21 Apr 2016 22:54:38 +0200 Subject: [PATCH] implement RBF kernel function --- src/Phpml/Math/Kernel.php | 17 +++++++++++++ src/Phpml/Math/Kernel/RBF.php | 39 +++++++++++++++++++++++++++++ tests/Phpml/Math/Kernel/RBFTest.php | 26 +++++++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 src/Phpml/Math/Kernel.php create mode 100644 src/Phpml/Math/Kernel/RBF.php create mode 100644 tests/Phpml/Math/Kernel/RBFTest.php diff --git a/src/Phpml/Math/Kernel.php b/src/Phpml/Math/Kernel.php new file mode 100644 index 0000000..776f78c --- /dev/null +++ b/src/Phpml/Math/Kernel.php @@ -0,0 +1,17 @@ +gamma = $gamma; + } + + /** + * @param float $a + * @param float $b + * + * @return float + */ + public function compute($a, $b) + { + $score = 2 * Product::scalar($a, $b); + $squares = Product::scalar($a, $a) + Product::scalar($b, $b); + $result = exp(-$this->gamma * ($squares - $score)); + + return $result; + } + +} diff --git a/tests/Phpml/Math/Kernel/RBFTest.php b/tests/Phpml/Math/Kernel/RBFTest.php new file mode 100644 index 0000000..cc22229 --- /dev/null +++ b/tests/Phpml/Math/Kernel/RBFTest.php @@ -0,0 +1,26 @@ +assertEquals(1, $rbf->compute([1, 2], [1, 2])); + $this->assertEquals(0.97336, $rbf->compute([1, 2, 3], [4, 5, 6]), '', $delta = 0.0001); + $this->assertEquals(0.00011, $rbf->compute([4, 5], [1, 100]), '', $delta = 0.0001); + + $rbf = new RBF($gamma = 0.2); + + $this->assertEquals(1, $rbf->compute([1, 2], [1, 2])); + $this->assertEquals(0.00451, $rbf->compute([1, 2, 3], [4, 5, 6]), '', $delta = 0.0001); + $this->assertEquals(0, $rbf->compute([4, 5], [1, 100])); + } + +}