forked from jorgecasas/php-ml
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement ColumnFilter preprocessor (#378)
- Loading branch information
Showing
2 changed files
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Phpml\Preprocessing; | ||
|
||
final class ColumnFilter implements Preprocessor | ||
{ | ||
/** | ||
* @var string[] | ||
*/ | ||
private $datasetColumns = []; | ||
|
||
/** | ||
* @var string[] | ||
*/ | ||
private $filterColumns = []; | ||
|
||
public function __construct(array $datasetColumns, array $filterColumns) | ||
{ | ||
$this->datasetColumns = array_map(static function (string $column): string { | ||
return $column; | ||
}, $datasetColumns); | ||
$this->filterColumns = array_map(static function (string $column): string { | ||
return $column; | ||
}, $filterColumns); | ||
} | ||
|
||
public function fit(array $samples, ?array $targets = null): void | ||
{ | ||
//nothing to do | ||
} | ||
|
||
public function transform(array &$samples, ?array &$targets = null): void | ||
{ | ||
$keys = array_intersect($this->datasetColumns, $this->filterColumns); | ||
|
||
foreach ($samples as &$sample) { | ||
$sample = array_values(array_intersect_key($sample, $keys)); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Phpml\Tests\Preprocessing; | ||
|
||
use Phpml\Preprocessing\ColumnFilter; | ||
use PHPUnit\Framework\TestCase; | ||
|
||
final class ColumnFilterTest extends TestCase | ||
{ | ||
public function testFilterColumns(): void | ||
{ | ||
$datasetColumns = ['age', 'income', 'kids', 'beersPerWeek']; | ||
$filterColumns = ['income', 'beersPerWeek']; | ||
$samples = [ | ||
[21, 100000, 1, 4], | ||
[35, 120000, 0, 12], | ||
[33, 200000, 4, 0], | ||
]; | ||
|
||
$filter = new ColumnFilter($datasetColumns, $filterColumns); | ||
$filter->transform($samples); | ||
|
||
self::assertEquals([[100000, 4], [120000, 12], [200000, 0]], $samples); | ||
} | ||
} |