Passed
Push — master ( c44f3b...492344 )
by Arkadiusz
02:48
created

Optimizer::__construct()   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
abstract class Optimizer
8
{
9
    /**
10
     * Unknown variables to be found
11
     *
12
     * @var array
13
     */
14
    protected $theta;
15
16
    /**
17
     * Number of dimensions
18
     *
19
     * @var int
20
     */
21
    protected $dimensions;
22
23
    /**
24
     * Inits a new instance of Optimizer for the given number of dimensions
25
     *
26
     * @param int $dimensions
27
     */
28
    public function __construct(int $dimensions)
29
    {
30
        $this->dimensions = $dimensions;
31
32
        // Inits the weights randomly
33
        $this->theta = [];
34
        for ($i=0; $i < $this->dimensions; $i++) {
35
            $this->theta[] = rand() / (float) getrandmax();
36
        }
37
    }
38
39
    /**
40
     * Sets the weights manually
41
     *
42
     * @param array $theta
43
     */
44
    public function setInitialTheta(array $theta)
45
    {
46
        if (count($theta) != $this->dimensions) {
47
            throw new \Exception("Number of values in the weights array should be $this->dimensions");
48
        }
49
50
        $this->theta = $theta;
51
52
        return $this;
53
    }
54
55
    /**
56
     * Executes the optimization with the given samples & targets
57
     * and returns the weights
58
     *
59
     */
60
    abstract protected function runOptimization(array $samples, array $targets, \Closure $gradientCb);
61
}
62