1
|
|
|
<?php |
2
|
|
|
namespace MachineLearning\Domain\Hypothesis; |
3
|
|
|
|
4
|
|
|
use MachineLearning\Domain\Exception\WrongVariableForHypothesisException; |
5
|
|
|
use MachineLearning\Domain\Model\Result; |
6
|
|
|
use MachineLearning\Domain\Model\Value\VectorValue; |
7
|
|
|
use MachineLearning\Domain\Model\Value\ScalarValue; |
8
|
|
|
use MachineLearning\Domain\Model\ValueInterface; |
9
|
|
|
|
10
|
|
|
class Linear implements HypothesisInterface |
11
|
|
|
{ |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @inheritdoc |
15
|
|
|
*/ |
16
|
2 |
|
public function calculate(ValueInterface $coefficient, ValueInterface $variable) |
17
|
|
|
{ |
18
|
2 |
|
if (! $variable instanceof VectorValue) { |
19
|
|
|
throw new WrongVariableForHypothesisException(); |
20
|
|
|
} |
21
|
|
|
|
22
|
2 |
|
list($offset, $firstOrderCoefficients) = $this->getParameters($coefficient, $variable); |
23
|
|
|
|
24
|
2 |
|
$value = $offset+$variable->scalar($firstOrderCoefficients); |
25
|
2 |
|
return new ScalarValue($value); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @inheritdoc |
30
|
|
|
*/ |
31
|
2 |
|
public function derivative(ValueInterface $coefficient, ValueInterface $variable, $partialVariable) |
32
|
|
|
{ |
33
|
2 |
|
if (! $variable instanceof VectorValue) { |
34
|
|
|
throw new WrongVariableForHypothesisException(); |
35
|
|
|
} |
36
|
|
|
|
37
|
2 |
|
$x = $variable->getValue(); |
38
|
|
|
|
39
|
2 |
|
return new ScalarValue($x[$partialVariable]); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @inheritdoc |
44
|
|
|
*/ |
45
|
2 |
|
public function createResultFromData(array $data) |
46
|
|
|
{ |
47
|
2 |
|
return new Result( |
48
|
2 |
|
new VectorValue($data[0]), |
49
|
2 |
|
new ScalarValue($data[1]) |
50
|
2 |
|
); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param ValueInterface $coefficient |
56
|
|
|
* @param ValueInterface $variable |
57
|
|
|
* @return array |
58
|
|
|
*/ |
59
|
2 |
|
protected function getParameters(ValueInterface $coefficient, ValueInterface $variable) |
|
|
|
|
60
|
|
|
{ |
61
|
2 |
|
$coefficientValues = $coefficient->getValue(); //e.g. [1,1,3] |
|
|
|
|
62
|
|
|
|
63
|
2 |
|
$offset = $coefficientValues[0]; |
64
|
2 |
|
array_shift($coefficientValues); |
65
|
|
|
|
66
|
2 |
|
$firstOrderCoefficients = new VectorValue($coefficientValues); |
67
|
|
|
|
68
|
2 |
|
return array($offset, $firstOrderCoefficients); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.