1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare (strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Phpml\SupportVectorMachine; |
6
|
|
|
|
7
|
|
|
class DataTransformer |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @param array $samples |
11
|
|
|
* @param array $labels |
12
|
|
|
* |
13
|
|
|
* @return string |
14
|
|
|
*/ |
15
|
|
|
public static function trainingSet(array $samples, array $labels): string |
16
|
|
|
{ |
17
|
|
|
$set = ''; |
18
|
|
|
$numericLabels = self::numericLabels($labels); |
19
|
|
|
foreach ($labels as $index => $label) { |
20
|
|
|
$set .= sprintf('%s %s %s', $numericLabels[$label], self::sampleRow($samples[$index]), PHP_EOL); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
return $set; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param array $samples |
28
|
|
|
* |
29
|
|
|
* @return string |
30
|
|
|
*/ |
31
|
|
|
public static function testSet(array $samples): string |
32
|
|
|
{ |
33
|
|
|
$set = ''; |
34
|
|
|
foreach ($samples as $sample) { |
35
|
|
|
$set .= sprintf('0 %s %s', self::sampleRow($sample), PHP_EOL); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
return $set; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param string $resultString |
43
|
|
|
* @param array $labels |
44
|
|
|
* |
45
|
|
|
* @return array |
46
|
|
|
*/ |
47
|
|
|
public static function results(string $resultString, array $labels): array |
48
|
|
|
{ |
49
|
|
|
$numericLabels = self::numericLabels($labels); |
50
|
|
|
$results = []; |
51
|
|
|
foreach (explode(PHP_EOL, $resultString) as $result) { |
52
|
|
|
$results[] = array_search($result, $numericLabels); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return $results; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param array $labels |
60
|
|
|
* |
61
|
|
|
* @return array |
62
|
|
|
*/ |
63
|
|
|
public static function numericLabels(array $labels): array |
64
|
|
|
{ |
65
|
|
|
$numericLabels = []; |
66
|
|
|
foreach ($labels as $label) { |
67
|
|
|
if (isset($numericLabels[$label])) { |
68
|
|
|
continue; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
$numericLabels[$label] = count($numericLabels); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $numericLabels; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param array $sample |
79
|
|
|
* |
80
|
|
|
* @return string |
81
|
|
|
*/ |
82
|
|
|
private static function sampleRow(array $sample): string |
83
|
|
|
{ |
84
|
|
|
$row = []; |
85
|
|
|
foreach ($sample as $index => $feature) { |
86
|
|
|
$row[] = sprintf('%s:%s', $index + 1, $feature); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
return implode(' ', $row); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|