function softmax($x) { $exp = array_map('exp', $x); $sum_exp = array_sum($exp); return array_map(function ($val) use ($sum_exp) { return $val / $sum_exp; }, $exp); } function un_softmax($x) { $s = softmax($x); $jacobian = []; for ($i = 0; $i < count($s); $i++) { for ($j = 0; $j < count($s); $j++) { if ($i == $j) { $jacobian[$i][$j] = $s[$i] * (1 - $s[$i]); } else { $jacobian[$i][$j] = -$s[$i] * $s[$j]; } } } return $jacobian; }