Optimizer   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 12
dl 0
loc 51
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A theta() 0 3 1
A __construct() 0 8 2
A setTheta() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml\Helper\Optimizer;
6
7
use Closure;
8
use Phpml\Exception\InvalidArgumentException;
9
10
abstract class Optimizer
11
{
12
    /**
13
     * Unknown variables to be found
14
     *
15
     * @var array
16
     */
17
    protected $theta = [];
18
19
    /**
20
     * Number of dimensions
21
     *
22
     * @var int
23
     */
24
    protected $dimensions;
25
26
    /**
27
     * Inits a new instance of Optimizer for the given number of dimensions
28
     */
29
    public function __construct(int $dimensions)
30
    {
31
        $this->dimensions = $dimensions;
32
33
        // Inits the weights randomly
34
        $this->theta = [];
35
        for ($i = 0; $i < $this->dimensions; ++$i) {
36
            $this->theta[] = (random_int(0, PHP_INT_MAX) / PHP_INT_MAX) + 0.1;
37
        }
38
    }
39
40
    public function setTheta(array $theta): self
41
    {
42
        if (count($theta) !== $this->dimensions) {
43
            throw new InvalidArgumentException(sprintf('Number of values in the weights array should be %s', $this->dimensions));
44
        }
45
46
        $this->theta = $theta;
47
48
        return $this;
49
    }
50
51
    public function theta(): array
52
    {
53
        return $this->theta;
54
    }
55
56
    /**
57
     * Executes the optimization with the given samples & targets
58
     * and returns the weights
59
     */
60
    abstract public function runOptimization(array $samples, array $targets, Closure $gradientCb): array;
61
}
62