/** * Calculates the standard error of each of the regression coefficients. * * @return array */ public function getStandardErrorCoefficients() : array { if (is_null($this->SCoefficients)) { $design = new Matrix($this->observations->getFeatures()); $inverted = $design->transpose()->multiplyMatrix($design)->inverse(); $diagonalVector = []; for ($i = 0, $size = $inverted->getRowCount(); $i < $size; $i++) { $diagonalVector[] = $inverted->get($i, $i); } $this->SCoefficients = (new Matrix([$diagonalVector]))->multiplyScalar($this->getMeanSquaredError())->map(function ($element) { return sqrt($element); })->toArray()[0]; } return $this->SCoefficients; }
/** * @param Observations $observations * @return array * @throws InvalidArgumentException */ public function regress(Observations $observations) : array { $design = new Matrix($observations->getFeatures()); $observed = (new Matrix([$observations->getOutcomes()]))->transpose(); if ($design->getRowCount() < $design->getColumnCount()) { throw new InvalidArgumentException('Not enough observations to perform regression. You need to have more observations than explanatory variables.'); } $designTranspose = $design->transpose(); $prediction = $designTranspose->multiplyMatrix($design)->inverse()->multiplyMatrix($designTranspose->multiplyMatrix($observed)); return $prediction->transpose()->toArray()[0]; }