|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rubix\ML\Tests\NeuralNet\Optimizers\Stochastic; |
| 6 | + |
| 7 | +use Generator; |
| 8 | +use NDArray; |
| 9 | +use NumPower; |
| 10 | +use PHPUnit\Framework\Attributes\CoversClass; |
| 11 | +use PHPUnit\Framework\Attributes\DataProvider; |
| 12 | +use PHPUnit\Framework\Attributes\Group; |
| 13 | +use PHPUnit\Framework\Attributes\Test; |
| 14 | +use PHPUnit\Framework\Attributes\TestDox; |
| 15 | +use PHPUnit\Framework\TestCase; |
| 16 | +use Rubix\ML\Exceptions\InvalidArgumentException; |
| 17 | +use Rubix\ML\NeuralNet\Parameters\Parameter; |
| 18 | +use Rubix\ML\NeuralNet\Optimizers\Stochastic\Stochastic; |
| 19 | + |
| 20 | +#[Group('Optimizers')] |
| 21 | +#[CoversClass(Stochastic::class)] |
| 22 | +class StochasticTest extends TestCase |
| 23 | +{ |
| 24 | + protected Stochastic $optimizer; |
| 25 | + |
| 26 | + public static function stepProvider() : Generator |
| 27 | + { |
| 28 | + yield [ |
| 29 | + new Parameter(NumPower::array([ |
| 30 | + [0.1, 0.6, -0.4], |
| 31 | + [0.5, 0.6, -0.4], |
| 32 | + [0.1, 0.1, -0.7], |
| 33 | + ])), |
| 34 | + NumPower::array([ |
| 35 | + [0.01, 0.05, -0.02], |
| 36 | + [-0.01, 0.02, 0.03], |
| 37 | + [0.04, -0.01, -0.5], |
| 38 | + ]), |
| 39 | + [ |
| 40 | + [0.00001, 0.00005, -0.00002], |
| 41 | + [-0.00001, 0.00002, 0.00003], |
| 42 | + [0.00004, -0.00001, -0.0005], |
| 43 | + ], |
| 44 | + ]; |
| 45 | + } |
| 46 | + |
| 47 | + protected function setUp() : void |
| 48 | + { |
| 49 | + $this->optimizer = new Stochastic(0.001); |
| 50 | + } |
| 51 | + |
| 52 | + #[Test] |
| 53 | + #[TestDox('Throws exception when constructed with invalid learning rate')] |
| 54 | + public function testConstructorWithInvalidRate() : void |
| 55 | + { |
| 56 | + $this->expectException(InvalidArgumentException::class); |
| 57 | + |
| 58 | + new Stochastic(0.0); |
| 59 | + } |
| 60 | + |
| 61 | + #[Test] |
| 62 | + #[TestDox('Can be cast to a string')] |
| 63 | + public function testToString() : void |
| 64 | + { |
| 65 | + self::assertEquals('Stochastic (rate: 0.001)', (string) $this->optimizer); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * @param Parameter $param |
| 70 | + * @param NDArray $gradient |
| 71 | + * @param list<list<float>> $expected |
| 72 | + */ |
| 73 | + #[DataProvider('stepProvider')] |
| 74 | + public function testStep(Parameter $param, NDArray $gradient, array $expected) : void |
| 75 | + { |
| 76 | + $step = $this->optimizer->step(param: $param, gradient: $gradient); |
| 77 | + |
| 78 | + self::assertEqualsWithDelta($expected, $step->toArray(), 1e-7); |
| 79 | + } |
| 80 | +} |
0 commit comments