/** * Calculates the sum-squared total of the regression. This is the sum * of the squared distances of observations from their average, a useful * measure to put the sum-squared error (SSE) and sum-squared model (SSM) * into context. * * @return float */ private function getSumSquaredTotal() : float { if (is_null($this->sumSquaredTotal)) { $average = array_sum($this->observations->getOutcomes()) / count($this->observations->getOutcomes()); $this->sumSquaredTotal = static::sumSquaredDifference($this->observations->getOutcomes(), $average); } return $this->sumSquaredTotal; }
/** * @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]; }