2016-06-15 14:04:09 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare (strict_types = 1);
|
|
|
|
|
|
|
|
namespace Phpml\FeatureExtraction;
|
|
|
|
|
2016-06-16 07:00:10 +00:00
|
|
|
use Phpml\Transformer;
|
|
|
|
|
2016-06-15 14:04:09 +00:00
|
|
|
class TfIdfTransformer implements Transformer
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @var array
|
|
|
|
*/
|
|
|
|
private $idf;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param array $samples
|
|
|
|
*
|
|
|
|
* @return array
|
|
|
|
*/
|
|
|
|
public function transform(array $samples): array
|
|
|
|
{
|
|
|
|
$this->countTokensFrequency($samples);
|
|
|
|
|
|
|
|
$count = count($samples);
|
|
|
|
foreach ($this->idf as &$value) {
|
|
|
|
$value = log($count / $value, 10);
|
|
|
|
}
|
|
|
|
|
|
|
|
foreach ($samples as &$sample) {
|
|
|
|
foreach ($sample as $index => &$feature) {
|
|
|
|
$feature = $feature * $this->idf[$index];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $samples;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param array $samples
|
|
|
|
*
|
|
|
|
* @return array
|
|
|
|
*/
|
|
|
|
private function countTokensFrequency(array $samples)
|
|
|
|
{
|
|
|
|
$this->idf = array_fill_keys(array_keys($samples[0]), 0);
|
|
|
|
|
|
|
|
foreach ($samples as $sample) {
|
|
|
|
foreach ($sample as $index => $count) {
|
|
|
|
if ($count > 0) {
|
|
|
|
++$this->idf[$index];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|