alpha = $alpha; $this->alpha2 = $alpha ** 2; } /** * Compute the loss score. * * @internal * * @param Matrix $output * @param Matrix $target * @return float */ public function compute(Matrix $output, Matrix $target) : float { return $target->subtract($output)->map([$this, '_compute'])->mean()->mean(); } /** * Calculate the gradient of the cost function with respect to the output. * * @internal * * @param Matrix $output * @param Matrix $target * @return Matrix */ public function differentiate(Matrix $output, Matrix $target) : Matrix { $alpha = $output->subtract($target); return $alpha->square() ->add($this->alpha2) ->pow(-0.5) ->multiply($alpha); } /** * @param float $z * @return float */ public function _compute(float $z) : float { return $this->alpha2 * (sqrt(1.0 + ($z / $this->alpha) ** 2) - 1.0); } /** * Return the string representation of the object. * * @internal * * @return string */ public function __toString() : string { return "Huber Loss (alpha: {$this->alpha})"; } }