Completed
Push — develop ( a2e8a8...95caef )
by Arkadiusz
02:53
created

SupportVectorMachine::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
rs 9.4285
cc 1
eloc 7
nc 1
nop 3
1
<?php
2
3
declare (strict_types = 1);
4
5
namespace Phpml\SupportVectorMachine;
6
7
class SupportVectorMachine
8
{
9
    /**
10
     * @var int
11
     */
12
    private $type;
13
14
    /**
15
     * @var int
16
     */
17
    private $kernel;
18
19
    /**
20
     * @var float
21
     */
22
    private $cost;
23
24
    /**
25
     * @var string
26
     */
27
    private $binPath;
28
29
    /**
30
     * @var
31
     */
32
    private $varPath;
33
34
    /**
35
     * @var string
36
     */
37
    private $model;
38
39
    /**
40
     * @param int   $type
41
     * @param int   $kernel
42
     * @param float $cost
43
     */
44
    public function __construct(int $type, int $kernel, float $cost)
45
    {
46
        $this->type = $type;
47
        $this->kernel = $kernel;
48
        $this->cost = $cost;
49
50
        $rootPath = realpath(implode(DIRECTORY_SEPARATOR, [dirname(__FILE__), '..', '..', '..'])).DIRECTORY_SEPARATOR;
51
52
        $this->binPath = $rootPath.'bin'.DIRECTORY_SEPARATOR.'libsvm'.DIRECTORY_SEPARATOR;
53
        $this->varPath = $rootPath.'var'.DIRECTORY_SEPARATOR;
54
    }
55
56
    /**
57
     * @param array $samples
58
     * @param array $labels
59
     */
60
    public function train(array $samples, array $labels)
61
    {
62
        $trainingSet = DataTransformer::trainingSet($samples, $labels);
63
        file_put_contents($trainingSetFileName = $this->varPath.uniqid(), $trainingSet);
64
        $modelFileName = $trainingSetFileName.'-model';
65
66
        $command = sprintf('%ssvm-train -s %s -t %s -c %s %s %s', $this->binPath, $this->type, $this->kernel, $this->cost, $trainingSetFileName, $modelFileName);
67
        $output = '';
68
        exec(escapeshellcmd($command), $output);
69
70
        $this->model = file_get_contents($modelFileName);
71
72
        unlink($trainingSetFileName);
73
        unlink($modelFileName);
74
    }
75
76
    /**
77
     * @return string
78
     */
79
    public function getModel()
80
    {
81
        return $this->model;
82
    }
83
}
84