|
| 1 | +<?php |
| 2 | +/* |
| 3 | +MIT License |
| 4 | +----------- |
| 5 | +
|
| 6 | +Copyright (c) 2021 Seyit Düzoylum |
| 7 | +Permission is hereby granted, free of charge, to any person |
| 8 | +obtaining a copy of this software and associated documentation |
| 9 | +files (the "Software"), to deal in the Software without |
| 10 | +restriction, including without limitation the rights to use, |
| 11 | +copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 12 | +copies of the Software, and to permit persons to whom the |
| 13 | +Software is furnished to do so, subject to the following |
| 14 | +conditions: |
| 15 | +
|
| 16 | +The above copyright notice and this permission notice shall be |
| 17 | +included in all copies or substantial portions of the Software. |
| 18 | +
|
| 19 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 20 | +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES |
| 21 | +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 22 | +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 23 | +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, |
| 24 | +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 25 | +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR |
| 26 | +OTHER DEALINGS IN THE SOFTWARE. |
| 27 | +*/ |
| 28 | +class Regression{ |
| 29 | + function mean($values){ |
| 30 | + return array_sum($values) / (float)(count($values)); |
| 31 | + } |
| 32 | + |
| 33 | + function variance($values) |
| 34 | + { |
| 35 | + $num_of_elements = count($values); |
| 36 | + $variance = 0; |
| 37 | + $mean = $this->mean($values); |
| 38 | + foreach($values as $i) |
| 39 | + { |
| 40 | + $variance += pow(($i - $mean), 2); |
| 41 | + } |
| 42 | + |
| 43 | + return (float)($variance); |
| 44 | + } |
| 45 | + |
| 46 | + function covariance($arr1, $arr2) |
| 47 | + { |
| 48 | + $n=count($arr1); |
| 49 | + $sum = 0; |
| 50 | + for($i = 0; $i < $n; $i++){ |
| 51 | + $sum = $sum + ($arr1[$i] - $this->mean($arr1)) * ($arr2[$i] - $this->mean($arr2)); |
| 52 | + } |
| 53 | + return $sum; |
| 54 | + } |
| 55 | + |
| 56 | + function coefficients($arr1, $arr2){ |
| 57 | + $arr1_mean = $this->mean($arr1); |
| 58 | + $arr2_mean = $this->mean($arr2); |
| 59 | + $b1 = $this->covariance($arr1, $arr2)/$this->variance($arr1); |
| 60 | + $b0 = $arr2_mean - $b1 * $arr1_mean; |
| 61 | + return (['b0' => $b0, 'b1' => $b1]); |
| 62 | + } |
| 63 | + |
| 64 | + function simple_linear_regression($train, $test){ |
| 65 | + $predictions = array(); |
| 66 | + $x = array_column($train, 'x'); |
| 67 | + $y = array_column($train, 'y'); |
| 68 | + $coef = $this->coefficients($x, $y); |
| 69 | + foreach ($test as $key => $value) { |
| 70 | + $pred = $coef['b0']+$coef['b1']*$value; |
| 71 | + array_push($predictions, $pred); |
| 72 | + } |
| 73 | + return $predictions; |
| 74 | + } |
| 75 | +} |
0 commit comments