From 8544cf7083bb90214c251c394a18a9f2e36b9e22 Mon Sep 17 00:00:00 2001 From: Arkadiusz Kondas Date: Fri, 10 May 2019 23:10:05 +0200 Subject: [PATCH] Implement regression metrics (#373) --- src/Metric/Regression.php | 86 +++++++++++++++++++++++++++++ tests/Metric/RegressionTest.php | 97 +++++++++++++++++++++++++++++++++ 2 files changed, 183 insertions(+) create mode 100644 src/Metric/Regression.php create mode 100644 tests/Metric/RegressionTest.php diff --git a/src/Metric/Regression.php b/src/Metric/Regression.php new file mode 100644 index 0000000..9f0e024 --- /dev/null +++ b/src/Metric/Regression.php @@ -0,0 +1,86 @@ + $target) { + $errors[] = (($target - $predictions[$index]) ** 2); + } + + return Mean::arithmetic($errors); + } + + public static function meanSquaredLogarithmicError(array $targets, array $predictions): float + { + self::assertCountEquals($targets, $predictions); + + $errors = []; + foreach ($targets as $index => $target) { + $errors[] = (log(1 + $target) - log(1 + $predictions[$index])) ** 2; + } + + return Mean::arithmetic($errors); + } + + public static function meanAbsoluteError(array $targets, array $predictions): float + { + self::assertCountEquals($targets, $predictions); + + $errors = []; + foreach ($targets as $index => $target) { + $errors[] = abs($target - $predictions[$index]); + } + + return Mean::arithmetic($errors); + } + + public static function medianAbsoluteError(array $targets, array $predictions): float + { + self::assertCountEquals($targets, $predictions); + + $errors = []; + foreach ($targets as $index => $target) { + $errors[] = abs($target - $predictions[$index]); + } + + return (float) Mean::median($errors); + } + + public static function r2Score(array $targets, array $predictions): float + { + self::assertCountEquals($targets, $predictions); + + return Correlation::pearson($targets, $predictions) ** 2; + } + + public static function maxError(array $targets, array $predictions): float + { + self::assertCountEquals($targets, $predictions); + + $errors = []; + foreach ($targets as $index => $target) { + $errors[] = abs($target - $predictions[$index]); + } + + return (float) max($errors); + } + + private static function assertCountEquals(array &$targets, array &$predictions): void + { + if (count($targets) !== count($predictions)) { + throw new InvalidArgumentException('Targets count must be equal with predictions count'); + } + } +} diff --git a/tests/Metric/RegressionTest.php b/tests/Metric/RegressionTest.php new file mode 100644 index 0000000..1f75cfd --- /dev/null +++ b/tests/Metric/RegressionTest.php @@ -0,0 +1,97 @@ +