Implement LambdaTransformer (#381)

This commit is contained in:
Arkadiusz Kondas 2019-05-13 22:10:34 +02:00 committed by GitHub
parent c1c9873bf1
commit ff118eb2ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 0 deletions

View File

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Phpml\Preprocessing;
final class LambdaTransformer implements Preprocessor
{
/**
* @var callable
*/
private $lambda;
public function __construct(callable $lambda)
{
$this->lambda = $lambda;
}
public function fit(array $samples, ?array $targets = null): void
{
// nothing to do
}
public function transform(array &$samples, ?array &$targets = null): void
{
foreach ($samples as &$sample) {
$sample = call_user_func($this->lambda, $sample);
}
}
}

View File

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Phpml\Tests\Preprocessing;
use Phpml\Preprocessing\LambdaTransformer;
use PHPUnit\Framework\TestCase;
final class LambdaTransformerTest extends TestCase
{
public function testLambdaSampleTransformation(): void
{
$transformer = new LambdaTransformer(static function ($sample): int {
return $sample[0] + $sample[1];
});
$samples = [
[1, 2],
[3, 4],
[5, 6],
];
$transformer->transform($samples);
self::assertEquals([3, 7, 11], $samples);
}
}