Completed
Push — develop ( af3b57...b5e4cb )
by Arkadiusz
02:26
created

LeastSquares::predict()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
declare (strict_types = 1);
4
5
namespace Phpml\Regression;
6
7
use Phpml\Math\Statistic\Correlation;
8
use Phpml\Math\Statistic\StandardDeviation;
9
use Phpml\Math\Statistic\Mean;
10
11
class LeastSquares implements Regression
12
{
13
    /**
14
     * @var array
15
     */
16
    private $features;
17
18
    /**
19
     * @var array
20
     */
21
    private $targets;
22
23
    /**
24
     * @var float
25
     */
26
    private $slope;
27
28
    /**
29
     * @var
30
     */
31
    private $intercept;
32
33
    /**
34
     * @param array $features
35
     * @param array $targets
36
     */
37
    public function train(array $features, array $targets)
38
    {
39
        $this->features = $features;
40
        $this->targets = $targets;
41
42
        $this->computeSlope();
43
        $this->computeIntercept();
44
    }
45
46
    /**
47
     * @param float $feature
48
     *
49
     * @return mixed
50
     */
51
    public function predict($feature)
52
    {
53
        return $this->intercept + ($this->slope * $feature);
54
    }
55
56
    private function computeSlope()
57
    {
58
        $correlation = Correlation::pearson($this->features, $this->targets);
59
        $sdX = StandardDeviation::population($this->features);
60
        $sdY = StandardDeviation::population($this->targets);
61
62
        $this->slope = $correlation * ($sdY / $sdX);
63
    }
64
65
    private function computeIntercept()
66
    {
67
        $meanY = Mean::arithmetic($this->targets);
68
        $meanX = Mean::arithmetic($this->features);
69
70
        $this->intercept = $meanY - ($this->slope * $meanX);
71
    }
72
}
73