Passed
Push — master ( 55749c...a40c50 )
by
unknown
02:34
created

Optimizer::setTheta()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
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)
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
    /**
52
     * Executes the optimization with the given samples & targets
53
     * and returns the weights
54
     */
55
    abstract public function runOptimization(array $samples, array $targets, Closure $gradientCb);
56
}
57