2016-05-05 21:29:11 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare (strict_types = 1);
|
|
|
|
|
|
|
|
namespace Phpml\SupportVectorMachine;
|
|
|
|
|
|
|
|
class DataTransformer
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @param array $samples
|
|
|
|
* @param array $labels
|
|
|
|
*
|
|
|
|
* @return string
|
|
|
|
*/
|
|
|
|
public static function trainingSet(array $samples, array $labels): string
|
|
|
|
{
|
|
|
|
$set = '';
|
|
|
|
$numericLabels = self::numericLabels($labels);
|
|
|
|
foreach ($labels as $index => $label) {
|
|
|
|
$set .= sprintf('%s %s %s', $numericLabels[$label], self::sampleRow($samples[$index]), PHP_EOL);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $set;
|
|
|
|
}
|
|
|
|
|
2016-05-06 20:38:50 +00:00
|
|
|
/**
|
|
|
|
* @param array $samples
|
|
|
|
*
|
|
|
|
* @return string
|
|
|
|
*/
|
|
|
|
public static function testSet(array $samples): string
|
|
|
|
{
|
2016-05-07 20:17:12 +00:00
|
|
|
if (!is_array($samples[0])) {
|
|
|
|
$samples = [$samples];
|
|
|
|
}
|
|
|
|
|
2016-05-06 20:38:50 +00:00
|
|
|
$set = '';
|
|
|
|
foreach ($samples as $sample) {
|
|
|
|
$set .= sprintf('0 %s %s', self::sampleRow($sample), PHP_EOL);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $set;
|
|
|
|
}
|
|
|
|
|
2016-05-06 20:55:41 +00:00
|
|
|
/**
|
2016-05-07 20:17:12 +00:00
|
|
|
* @param string $rawPredictions
|
2016-05-06 20:55:41 +00:00
|
|
|
* @param array $labels
|
|
|
|
*
|
|
|
|
* @return array
|
|
|
|
*/
|
2016-05-07 20:17:12 +00:00
|
|
|
public static function predictions(string $rawPredictions, array $labels): array
|
2016-05-06 20:55:41 +00:00
|
|
|
{
|
|
|
|
$numericLabels = self::numericLabels($labels);
|
|
|
|
$results = [];
|
2016-05-07 20:17:12 +00:00
|
|
|
foreach (explode(PHP_EOL, $rawPredictions) as $result) {
|
|
|
|
if (strlen($result) > 0) {
|
|
|
|
$results[] = array_search($result, $numericLabels);
|
|
|
|
}
|
2016-05-06 20:55:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return $results;
|
|
|
|
}
|
|
|
|
|
2016-05-05 21:29:11 +00:00
|
|
|
/**
|
|
|
|
* @param array $labels
|
|
|
|
*
|
|
|
|
* @return array
|
|
|
|
*/
|
|
|
|
public static function numericLabels(array $labels): array
|
|
|
|
{
|
|
|
|
$numericLabels = [];
|
|
|
|
foreach ($labels as $label) {
|
|
|
|
if (isset($numericLabels[$label])) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
$numericLabels[$label] = count($numericLabels);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $numericLabels;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param array $sample
|
|
|
|
*
|
|
|
|
* @return string
|
|
|
|
*/
|
|
|
|
private static function sampleRow(array $sample): string
|
|
|
|
{
|
|
|
|
$row = [];
|
|
|
|
foreach ($sample as $index => $feature) {
|
2016-05-06 20:33:04 +00:00
|
|
|
$row[] = sprintf('%s:%s', $index + 1, $feature);
|
2016-05-05 21:29:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return implode(' ', $row);
|
|
|
|
}
|
|
|
|
}
|