MtCarsPLS1ScaleFalseTest.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace MathPHP\Tests\Statistics\Multivariate\PLS;
  3. use MathPHP\Exception;
  4. use MathPHP\LinearAlgebra\Matrix;
  5. use MathPHP\LinearAlgebra\MatrixFactory;
  6. use MathPHP\SampleData;
  7. use MathPHP\Statistics\Multivariate\PLS;
  8. class MtCarsPLS1ScaleFalseTest extends \PHPUnit\Framework\TestCase
  9. {
  10. /** @var PLS */
  11. private static $pls;
  12. /** @var Matrix */
  13. private static $X;
  14. /** @var Matrix */
  15. private static $Y;
  16. /**
  17. * R code for expected values:
  18. * library(chemometrics)
  19. * X = mtcars[,c(2:7, 10:11)]
  20. * Y = mtcars[,c(1)]
  21. * pls.model = pls2_nipals(X, Y, 1)
  22. *
  23. * @throws Exception\MathException
  24. */
  25. public static function setUpBeforeClass(): void
  26. {
  27. $mtCars = new SampleData\MtCars();
  28. // Remove any categorical variables
  29. $continuous = MatrixFactory::create($mtCars->getData())
  30. ->columnExclude(8)
  31. ->columnExclude(7);
  32. // Exclude mpg.
  33. self::$X = $continuous->columnExclude(0);
  34. // Just grab column 0.
  35. self::$Y = $continuous->submatrix(0, 0, $continuous->getM() - 1, 0);
  36. self::$pls = new PLS(self::$X, self::$Y, 1, false);
  37. }
  38. /**
  39. * @test Construction
  40. * @throws Exception\MathException
  41. */
  42. public function testConstruction()
  43. {
  44. // When
  45. $pls = new PLS(self::$X, self::$Y, 1, false);
  46. // Then
  47. $this->assertInstanceOf(PLS::class, $pls);
  48. }
  49. /**
  50. * @test The class returns the correct values for B
  51. *
  52. * R code for expected values:
  53. * pls.model$B
  54. */
  55. public function testB()
  56. {
  57. // Given
  58. $expected = [
  59. [-0.0004929300],
  60. [-0.0340230796],
  61. [-0.0172363614],
  62. [0.0001179642],
  63. [-0.0002749742],
  64. [0.0002423248],
  65. [0.0001147732],
  66. [-0.0002882169],
  67. ];
  68. // When
  69. $B = self::$pls->getCoefficients()->getMatrix();
  70. // Then
  71. $this->assertEqualsWithDelta($expected, $B, .00001);
  72. }
  73. }