2016-04-08 22:11:59 +02:00
|
|
|
<?php
|
2016-04-08 22:49:17 +02:00
|
|
|
|
2016-11-20 22:53:17 +01:00
|
|
|
declare(strict_types=1);
|
2016-04-08 22:11:59 +02:00
|
|
|
|
2018-01-06 13:09:33 +01:00
|
|
|
namespace Phpml\Tests\Metric;
|
2016-04-08 22:11:59 +02:00
|
|
|
|
2016-05-31 20:01:54 +02:00
|
|
|
use Phpml\Classification\SVC;
|
|
|
|
use Phpml\CrossValidation\RandomSplit;
|
2016-09-30 14:02:08 +02:00
|
|
|
use Phpml\Dataset\Demo\IrisDataset;
|
2017-11-28 08:00:13 +01:00
|
|
|
use Phpml\Exception\InvalidArgumentException;
|
2016-04-08 22:11:59 +02:00
|
|
|
use Phpml\Metric\Accuracy;
|
2016-05-31 20:01:54 +02:00
|
|
|
use Phpml\SupportVectorMachine\Kernel;
|
2017-02-03 12:58:25 +01:00
|
|
|
use PHPUnit\Framework\TestCase;
|
2016-04-08 22:11:59 +02:00
|
|
|
|
2017-02-03 12:58:25 +01:00
|
|
|
class AccuracyTest extends TestCase
|
2016-04-08 22:11:59 +02:00
|
|
|
{
|
2017-11-14 21:21:23 +01:00
|
|
|
public function testThrowExceptionOnInvalidArguments(): void
|
2016-04-08 22:11:59 +02:00
|
|
|
{
|
2017-11-28 08:00:13 +01:00
|
|
|
$this->expectException(InvalidArgumentException::class);
|
2016-04-08 22:11:59 +02:00
|
|
|
$actualLabels = ['a', 'b', 'a', 'b'];
|
|
|
|
$predictedLabels = ['a', 'a'];
|
|
|
|
Accuracy::score($actualLabels, $predictedLabels);
|
|
|
|
}
|
|
|
|
|
2017-11-14 21:21:23 +01:00
|
|
|
public function testCalculateNormalizedScore(): void
|
2016-04-08 22:11:59 +02:00
|
|
|
{
|
|
|
|
$actualLabels = ['a', 'b', 'a', 'b'];
|
|
|
|
$predictedLabels = ['a', 'a', 'b', 'b'];
|
|
|
|
|
|
|
|
$this->assertEquals(0.5, Accuracy::score($actualLabels, $predictedLabels));
|
|
|
|
}
|
|
|
|
|
2017-11-14 21:21:23 +01:00
|
|
|
public function testCalculateNotNormalizedScore(): void
|
2016-04-08 22:11:59 +02:00
|
|
|
{
|
|
|
|
$actualLabels = ['a', 'b', 'a', 'b'];
|
|
|
|
$predictedLabels = ['a', 'b', 'b', 'b'];
|
|
|
|
|
|
|
|
$this->assertEquals(3, Accuracy::score($actualLabels, $predictedLabels, false));
|
|
|
|
}
|
2016-05-31 20:01:54 +02:00
|
|
|
|
2017-11-14 21:21:23 +01:00
|
|
|
public function testAccuracyOnDemoDataset(): void
|
2016-05-31 20:01:54 +02:00
|
|
|
{
|
2016-09-30 14:02:08 +02:00
|
|
|
$dataset = new RandomSplit(new IrisDataset(), 0.5, 123);
|
2016-05-31 20:01:54 +02:00
|
|
|
|
|
|
|
$classifier = new SVC(Kernel::RBF);
|
|
|
|
$classifier->train($dataset->getTrainSamples(), $dataset->getTrainLabels());
|
|
|
|
|
2018-01-06 21:25:47 +01:00
|
|
|
$predicted = (array) $classifier->predict($dataset->getTestSamples());
|
2016-05-31 20:01:54 +02:00
|
|
|
|
|
|
|
$accuracy = Accuracy::score($dataset->getTestLabels(), $predicted);
|
|
|
|
|
2016-12-12 19:28:26 +01:00
|
|
|
$expected = PHP_VERSION_ID >= 70100 ? 1 : 0.959;
|
|
|
|
|
|
|
|
$this->assertEquals($expected, $accuracy, '', 0.01);
|
2016-05-31 20:01:54 +02:00
|
|
|
}
|
2016-04-08 22:11:59 +02:00
|
|
|
}
|